【leetcode】Partition List

Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 
最简答的,扫描两次链表
第一次找到所有比x小的节点,并保存下来
第二次找到所有比x大的节点,并保存下来
然后把他们两连起来
 
 
 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        

13         ListNode *p=head;

14         ListNode *p0=NULL;

15         ListNode *head1=NULL;

16         ListNode *head2=NULL;

17         while(p!=NULL)

18         {

19             ListNode *tmp;

20             if(p->val<x)

21             {

22                 tmp=new ListNode(p->val);

23                 if(p0==NULL) head1=tmp;

24                 else  p0->next=tmp;

25                 p0=tmp;

26             }

27            

28             p=p->next;

29         }

30        

31         ListNode *head1End=p0;

32         p=head;

33         p0=NULL;

34         while(p!=NULL)

35         {

36             ListNode *tmp;

37             if(p->val>=x)

38             {

39                 tmp=new ListNode(p->val);

40                 if(p0==NULL) head2=tmp;

41                 else p0->next=tmp;

42                 p0=tmp;

43             }

44             p=p->next;

45         }

46        

47        

48         if(head1End!=NULL) head1End->next=head2;

49         else head1=head2;

50        

51         return head1;

52     }

53 };

 

第二种思路,与第一种方法类似,只是不新建链表进行存储
 
 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        

13         if(head==NULL) return NULL;

14        

15         ListNode *p=head;

16        

17         ListNode *head1=NULL;

18         ListNode *head2=NULL;

19        

20         ListNode *p0=NULL;

21         ListNode *p1=NULL;

22        

23        

24        

25         while(p!=NULL)

26         {

27             if(p->val<x)

28             {

29                 if(p0==NULL) head1=p;

30                 else  p0->next=p;

31                 p0=p;

32             }

33             else

34             {

35                 if(p1==NULL) head2=p;

36                 else p1->next=p;

37                 p1=p;

38             }

39            

40             p=p->next;

41         }

42        

43         if(p1!=NULL) p1->next=NULL;

44         if(p0!=NULL) p0->next=head2;

45         else head1=head2;

46        

47         return head1;

48     }

49 };

 

你可能感兴趣的:(partition)