LC86 Partition List

有关链表的题目,很多都需要在编程前想好用多少个指针,比如链表反转的题目,就需要三个指针。这题需要额外四个指针,两个指针保存链表头,两个保存最后一个结点。

 1 class Solution{
 2     public:
 3     ListNode* partition(ListNode* head, int x) {
 4         if(head==NULL||head->next==NULL)
 5             return head;
 6         ListNode* p1=NULL;
 7         ListNode* p2=NULL;
 8         ListNode* tail1;
 9         ListNode* tail2;
10         while(head!=NULL)
11         {
12             if(head->val<x)
13             {
14                 if(p1==NULL)
15                 {
16                     p1=head;
17                     tail1=head;
18                 }
19                 else if(p1!=NULL)
20                 {
21                     tail1->next=head;
22                     tail1=head;
23                 }
24                 tail1->next=NULL;
25             }
26             else if(head->val>=x)
27             {
28                 if(p2==NULL)
29                 {
30                     p2=head;
31                     tail2=head;
32                 }
33                 else
34                 {
35                     tail2->next=head;
36                     tail2=head;
37                 }
38                 tail2->next=NULL;
39             }
40             head=head->next;
41         }
42         if(p1==NULL)
43             return p2;
44         else
45         {
46             tail1->next=p2;
47             return p1;
48         }
49     }
50 };
View Code

 

posted @ 2016-03-03 19:45  vaevaevae  阅读(218)  评论(0编辑  收藏  举报