[LintCode] 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.

Example

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

Algorithm:

1. create two dummy nodes for two possible sublists, one for all nodes < x, one for all nodes >= x;

2. iterate the input list, add nodes to either sublist accordingly and remove the existing link;

3. concat the two sublists.

Runtime: O(n), Space: O(1)

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param head: The first node of linked list
17      * @param x: An integer
18      * @return: A ListNode
19      */
20     public ListNode partition(ListNode head, int x) {   
21         if(head == null || head.next == null) {
22             return head;
23         }
24         ListNode dummyNode1 = new ListNode(0);
25         ListNode dummyNode2 = new ListNode(0);
26         ListNode endNode1 = dummyNode1, endNode2 = dummyNode2, temp = null;
27         ListNode curr = head;
28         while(curr != null) {
29             temp = curr.next;
30             if(curr.val < x) {
31                 endNode1.next = curr;
32                 endNode1 = curr;
33                 endNode1.next = null;
34             }
35             else {
36                 endNode2.next = curr;
37                 endNode2 = curr;
38                 endNode2.next = null;
39             }
40             curr = temp;
41         }
42         if(endNode1 == null) {
43             return dummyNode2.next;
44         }
45         endNode1.next = dummyNode2.next;
46         return dummyNode1.next;
47     }
48 }

Related Problems

Partition Array

原文地址:https://www.cnblogs.com/lz87/p/7498012.html