LeetCode:Partition List
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 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* partition(ListNode* head, int x) { 12 13 ListNode left_dummy(-1); 14 ListNode right_dummy(-1); 15 16 auto left_cur=&left_dummy; 17 auto right_cur=&right_dummy; 18 19 for(ListNode *cur=head;cur!=NULL;cur=cur->next) 20 { 21 if(cur->val<x) 22 { 23 left_cur->next=cur; 24 left_cur=cur; 25 } 26 else 27 { 28 right_cur->next=cur; 29 right_cur=cur; 30 } 31 } 32 left_cur->next=right_dummy.next; 33 right_cur->next=NULL; 34 35 return left_dummy.next; 36 } 37 };