Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
写了两份,思路都是一样的,第一个繁杂一点,第二个简明一点。
参考代码1:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if(!head)
return NULL;
ListNode *new_head = head, *p = head, *bigger_head = NULL, *pre=NULL, *bigger_cur=NULL;
while(new_head && new_head->val>=x)
new_head = new_head->next;
//all elems >= x
if(!new_head)
return head;
while(p)
{
if(p->val<x)
{
pre = p;
p = p->next;
}
else
{
if(!bigger_head)
bigger_cur = bigger_head = p;
else
{
bigger_cur->next = p;
bigger_cur = bigger_cur->next;
}
p = p->next;
while(p && p->val >= x)
{
bigger_cur = p;
p = p->next;
}
if(p)
{
if(!pre)
pre = p;
else
{
pre->next = p;
pre = p;
}
p = p->next;
}
}
}
if(bigger_cur)
bigger_cur->next = NULL;
if(pre)
pre->next = bigger_head;
return new_head;
}
};
参考代码2:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if(!head)
return NULL;
ListNode *newHead = NULL, *newTail=NULL, *biggerHead = NULL, *q = NULL, *p = head;
while(p)
{
if(p->val<x)
{
if(!newHead)
newTail = newHead = p;
else
newTail = newTail->next = p;
p = p->next;
}
else
{
if(!biggerHead)
q = biggerHead = p;
else
q = q->next = p;
p = p->next;
while(p && p->val>=x)
{
q = q->next = p;
p = p->next;
}
}
}
if(!newHead || !biggerHead)
return head;
newTail->next = biggerHead;
q->next = NULL;
return newHead;
}
};
//Solution 3:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if(!head)
return NULL;
ListNode *cur = head, *left = NULL, *right = NULL, *curLeft = NULL, *curRight = NULL;
while(cur) {
if(cur->val < x) {
if(left)
curLeft = curLeft->next = cur;
else
left = curLeft = cur;
} else {
if(right)
curRight = curRight->next = cur;
else
right = curRight = cur;
}
cur = cur->next;
}
if(left) {
curLeft->next = right;
if(right)
curRight->next = NULL;
return left;
} else {
curRight->next = NULL;
return right;
}
}
};