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
.
方法:扫一遍链表,通过与x比较,将链表分成两个链表,一个链表是<x的节点集,一个链表是>=x的节点集,代码如下:
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 if( !head ) return 0; 13 ListNode lnode(0); 14 ListNode rnode(0); 15 ListNode* lpre = &lnode; //<x的节点集,保证了节点间的相对顺序 16 ListNode* rpre = &rnode; //>=x的节点集,保证了节点间的相对顺序 17 while( head ) { 18 if( head->val < x ) { 19 lpre->next = head; 20 lpre = head; 21 head = head->next; 22 lpre->next = 0; 23 } 24 else { 25 rpre->next = head; 26 rpre = head; 27 head = head->next; 28 rpre->next = 0; 29 } 30 } 31 lpre->next = rnode.next; 32 return lnode.next; 33 } 34 };