代码改变世界

leetcode - Partition List

2013-11-11 22:44  张汉生  阅读(145)  评论(0编辑  收藏  举报

 

 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         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         if (head == NULL)
15             return head;
16         ListNode * ltail = NULL;
17         if (head->val < x)
18             ltail = head;
19         ListNode *itr = head->next, *last = head;
20         while (itr != NULL){
21             if (itr->val >= x){
22                 last = itr;
23                 itr = itr->next;
24                 continue;
25             }
26             if (last == ltail){
27                 ltail = itr;
28                 last = itr;
29                 itr = itr->next;
30                 continue;
31             }
32             last->next = itr->next;
33             if (ltail==NULL){
34                 itr->next = head;
35                 head = itr;
36             }
37             else {
38                 itr->next = ltail->next;
39                 ltail->next = itr;
40             }
41             ltail = itr;
42             itr = last->next;
43         }
44         return head;
45     }
46 };