创建两个链表small、big
遍历原来链表
比X小的节点尾插到small
比X大的节点尾插到big
最后来链接起来
这样不会改变各个节点的相对顺序
ListNode* partition(ListNode* pHead, int x) {
// write code here
struct ListNode* smallhead = NULL, * bighead = NULL;
struct ListNode* samlltail = NULL, * bigtail = NULL;
struct ListNode* cur = pHead;
while (cur) {
if (cur->val > x)
{
if (bighead == NULL)
{
bighead = bigtail = cur;
}
else
{
bigtail->next = cur;
bigtail = bigtail->next;
}
}
else
{
if (smallhead == NULL)
{
smallhead = samlltail = cur;
}
else
{
samlltail->next = cur;
samlltail = samlltail->next;
}
}
cur = cur->next;
}
bigtail->next = NULL;
samlltail->next = bighead;
return smallhead;
}