标签:des style blog io color ar sp for div
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
.
Solution:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode partition(ListNode head, int x) { 14 ListNode root=new ListNode(-1); 15 root.next=head; 16 ListNode small=root; 17 ListNode big=root; 18 ListNode pointer=root; 19 while(pointer.next!=null){ //在这里找第一个比x大或等的数 20 if(pointer.next.val>=x){ 21 small=pointer; 22 big=pointer.next; 23 pointer=pointer.next; 24 break; 25 } 26 pointer=pointer.next; 27 } 28 while(pointer.next!=null){ 29 if(pointer.next.val>=x){ 30 pointer=pointer.next; 31 big=big.next; 32 }else{ 33 pointer=pointer.next; 34 ListNode temp=pointer.next; 35 pointer.next=small.next; 36 small.next=pointer; 37 big.next=temp; 38 pointer=big; 39 small=small.next; 40 } 41 } 42 return root.next; 43 } 44 }
标签:des style blog io color ar sp for div
原文地址:http://www.cnblogs.com/Phoebe815/p/4101017.html