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.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode partition(ListNode head, int x) {
11         if (head == null || head.next == null) {
12             return head;
13         }
14         ListNode dummy = new ListNode(0);
15         dummy.next = head;
16         ListNode dummyBig = new ListNode(0);
17         ListNode curtSmall = dummy;
18         ListNode curtBig = dummyBig;
19         while (head != null) {
20             if (head.val < x) {
21                 curtSmall.next = head;
22                 curtSmall = curtSmall.next;
23             } else {
24                 curtBig.next = head;
25                 curtBig = curtBig.next;
26             }
27             head = head.next;
28         }
29         curtSmall.next = dummyBig.next;
30         curtBig.next = null;
31         return dummy.next;
32     }
33 }

 

posted @ 2016-08-16 09:23  YuriFLAG  阅读(142)  评论(0)    收藏  举报