码迷,mamicode.com
首页 > 其他好文 > 详细

86. Partition List

时间:2018-07-30 21:34:07      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:str   pre   新建   node   class   节点   art   直接   第一个   

 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

标签:str   pre   新建   node   class   节点   art   直接   第一个   

原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9392527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!