CoderJesse  
wangjiexi@CS.PKU

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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         ListNode *newhead = NULL;
15         ListNode *newtail = NULL;
16         ListNode *tmp = head;    
17         while(tmp != NULL)
18         {
19             if(tmp->val < x)
20             {
21                 if(newtail == NULL)
22                 {
23                     newtail = new ListNode(tmp->val);
24                     newhead = newtail;
25                 }
26                 else
27                 {
28                     newtail->next = new ListNode(tmp->val);
29                     newtail = newtail->next;
30                 }
31             }
32             tmp = tmp->next;
33         }
34         
35         tmp = head;
36         while(tmp != NULL)
37         {
38             if(tmp->val >= x)
39             {
40                 if(newtail == NULL)
41                 {
42                     newtail = new ListNode(tmp->val);
43                     newhead = newtail;
44                 }
45                 else
46                 {
47                     newtail->next = new ListNode(tmp->val);
48                     newtail = newtail->next;
49                 }
50             }
51             tmp = tmp->next;
52         }
53         return newhead;
54     }
55 };

 

posted on 2013-03-01 14:13  CoderJesse  阅读(100)  评论(0)    收藏  举报