[Leetcode 71] 86 Partition List

Problem:

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.

 

Analysis:

first parition the list into two sub-lists. sublist1 for those nodes that less than x, sublist 2 for those nodes that greater than or equal to x. Then merge them together. Remember to set the last node's next to NULL.

The split procedure takes O(n) time and the merger procedure takes O(1) time.

It's an in-place algorithm.

 

Code:

 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (head == NULL || head->next == NULL)
15             return head;
16         
17         ListNode *ls, *le, *gs, *ge;
18         ls = le = gs = ge = NULL;
19         
20         // split list
21         while (head != NULL) {
22             if (head->val < x) {
23                 if (ls == NULL) {
24                     ls = le = head;
25                 } else  {
26                     le->next = head;
27                     le = head;
28                 }
29             } else {
30                 if (gs == NULL) {
31                     gs = ge = head;
32                 } else {
33                     ge->next = head;
34                     ge = head;
35                 }
36             }
37             
38             head = head->next;
39         }
40         
41         // merge list
42         if (ls == NULL) {
43             ls = gs;
44             if (ge != NULL)
45                 ge->next = NULL;
46         } else {
47             le->next = gs;
48             if (ge != NULL)
49                 ge->next = NULL;
50         }
51         
52         return ls;
53     }
54 };
View Code

 

posted on 2013-07-21 13:01  freeneng  阅读(187)  评论(0编辑  收藏  举报

导航