Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R than or equal to x.
You should preserve the original relative order of the nodes in each of the.
For example,
Given 1->4->3->2->5->2 and x = 3,
Return 1->2->2->4->3->5 .
This problem requires us to divide the list and move all nodes that are smaller than the given value to the front, and the order of the nodes that are larger than that value is the same as a local sort. Then can be thought of a solution is to first find the first greater than or equal to the given value of the node, with the example given in the topic is to find 4, and then find the value of less than 3, each to find a place to take it out before 4 can, code as follows:
Solution One
classSolution { Public: ListNode*partition (ListNode *head,intx) {if(!head)returnHead; ListNode*dummy =NewListNode (-1); Dummy->next =Head; ListNode*cur = dummy, *pre = dummy, *p =Head; while(cur->next) { if(Cur->next->val <x) {if(Pre = =cur) {cur= cur->Next; Pre=cur; P= cur->Next; } Else{Pre->next = cur->Next; Pre= pre->Next; Cur->next = cur->next->Next; Pre->next=p; } } Else{cur= cur->Next; } } returnDummy->Next; }};
The sequence of the list changes for this solution is:
5, 2, 1, 4, 3
5, 3, 1, 2, 4
3, 4, 1, 2, 2
This problem also has a solution, that is, all nodes smaller than the given value to form a new linked list, the original linked list of the remaining node value is greater than or equal to the given value, as long as the original linked list is directly connected to the new linked list, the code is as follows:
Solution Two
classSolution { Public: ListNode*partition (ListNode *head,intx) {if(!head)returnHead; ListNode*dummy =NewListNode (-1); ListNode*newdummy =NewListNode (-1); Dummy->next =Head; ListNode*cur = dummy, *p =Newdummy; while(cur->next) { if(Cur->next->val <x) {p->next = cur->Next; P= p->Next; Cur->next = cur->next->Next; P->next =NULL; } Else{cur= cur->Next; }} P->next = dummy->Next; returnNewdummy->Next; }};
The sequence of changes in the chain table of this method is:
5, 2, 3, 4, original:1, 2
New:
2, 5, 3, 2, Original:4
New:1
3, 5, Original:4, 2
New:1-2
Original:4, 3, 5
New:1, 2, 2
Original:
3, 4, 2, 2, New:1, 5
[Leetcode] Partition List Broken lists