partion list

 1 class Solution {
 2 public:
 3     ListNode *partition(ListNode *head, int x) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if( !head )  return NULL;
 7         
 8         ListNode* ptr = new ListNode(0);
 9         ptr->next = head;
10                
11         ListNode * t = head;
12         ListNode * p = ptr;
13         ListNode *q;
14         while( t!=NULL && t->val<x)
15         {
16             p = p->next;
17             t = t->next;
18         } 
19         if( !t ) return ptr->next;
20         
21         while(true)
22         {
23             q = t;
24             t = t->next;
25             while( t && t-> val >= x )
26             {
27                 q = q->next;
28                 t = t->next;          
29             }
30             if( !t ) return ptr->next;
31         
32             t = p->next;
33             p->next = q->next;
34             q -> next = p->next->next;
35             p->next->next = t;
36         
37             p = p->next;
38             t = q;
39         }
40         return ptr->next;
41     
42         
43     }
44 };

 

posted on 2013-09-03 16:39  jumping_grass  阅读(142)  评论(0)    收藏  举报

导航