86. Partition List

Posted zhuangbijingdeboke

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了86. Partition List相关的知识,希望对你有一定的参考价值。

 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 {
11 public:
12     ListNode* partition(ListNode* head, int x) 
13     {
14         ListNode *small=head,*big=head,*pre,*rpre;
15         ListNode *res=new ListNode(0);
16         res->next=head;
17         pre=res;
18         while(big!=NULL&&big->val<x)
19         {
20             big=big->next;
21             pre=pre->next;
22         }
23         rpre=pre,small=big;
24         while(small!=NULL)
25         {
26             if(small->val<x)
27             {
28                 rpre->next=small->next;
29                 pre->next=small;
30                 small->next=big;
31                 pre=pre->next;
32                 small=rpre->next;
33             }
34             else
35             {
36                 small=small->next;
37                 rpre=rpre->next;
38             }
39         }
40         return res->next;
41     }
42 };

核心思路是把所有比给定值小的节点摘到第一个大于等于给定值的节点左边

也可以直接新建两个链表,把小的和大的分开放,然后拼在一起

 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 {
11 public:
12     ListNode* partition(ListNode* head, int x) 
13     {
14         ListNode *psmall=new ListNode(0);
15         ListNode *pbig=new ListNode(0);
16         ListNode *res=psmall,*k=pbig;
17         while(head!=NULL)
18         {
19             if(head->val<x)
20                 psmall=psmall->next=head;
21             else
22                 pbig=pbig->next=head;
23             head=head->next;
24         }
25         pbig->next=NULL;
26         psmall->next=k->next;
27         return res->next;
28     }
29 };

 

以上是关于86. Partition List的主要内容,如果未能解决你的问题,请参考以下文章

86. Partition List

86. Partition List

86. Partition List

[LeetCode]86. Partition List

86.Partition List

Leetcode 86. Partition List