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
.
设定两个头结点,一个用来连接大于等于x的结点,令一个用于连接小于x的结点,最后将大于的结点挂在小于x的结点的后面。
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
if(!head || !head->next) return head;
ListNode *big = new ListNode(1);
ListNode *small = new ListNode(-1);
ListNode *b = big;
ListNode *s = small;
ListNode *p = head;
while (head)
{
ListNode *pnext = head->next;
if(head->val >= x){
head->next = b->next;
b->next = head;
b = head;
}
else{
head->next = s->next;
s->next = head;
s = head;
}
head = pnext;
}
s->next = big->next;
head = small->next;
delete small;
delete big;
return head;
}
};