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.
For example,
Given 1->4->3->2->5->2 and x = 3,
Return 1->2->2->4->3->5.
Solution 1:
Note Use Dummynode to record the previous node of the head node of each chain. This allows us to easily retrieve the head node.
1. Go Through the link, find the nodes which is bigger than N, create a new link.
2. After 1 done, just link the other links.
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 * }Ten * } One */ A Public classSolution { - PublicListNode partition (ListNode head,intx) { - if(Head = =NULL) { the return NULL; - } - -ListNode dummy =NewListNode (0); +Dummy.next =head; - +ListNode pre =dummy; AListNode cur =head; at - //Record The big list. -ListNode Bigdummy =NewListNode (0); -ListNode Bigtail =Bigdummy; - - while(cur! =NULL) { in if(Cur.val >=x) { - //Unlink the cur; toPre.next =Cur.next; + - //ADD the cur to the tail of the new link. theBigtail.next =cur; *Cur.next =NULL; $ Panax Notoginseng //Refresh the Bigtail. -Bigtail =cur; the + //when you remove an element, the pre does not need to be modified because the cur has moved to the next position. A}Else { thePre =Pre.next; + } - $Cur =Pre.next; $ } - - //Link the Big linklist to the smaller one. thePre.next =Bigdummy.next; - Wuyi returnDummy.next; the } -}View Code
CODE:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/list/Partition.java
Leetcode:partition List Problem Solving report