Given a singly linked list l: l0→l1→ ... →ln-1→lN,
Reorder it to: l0→ln→l1→ln-1→l2→l N-2→ ...
You must does this in-place without altering the nodes ' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
Analysis:
- Break list in the middle to lists (use fast & slow pointers)
- Reverse The order of the second list
- Merge both list back together
Java Code:
20160601
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { Public voidreorderlist (ListNode head) {//1.find The middle node in the list and split it into the small list//2. Reverse the second list//3. Merge one halves into one long list//Base Case if(Head = =NULL|| Head.next = =NULL) { return; } ListNode Mid=Findmiddle (head); ListNode One=Head; ListNode=Mid.next; Mid.next=NULL; both=reverse (both); Merge (one, both); } PrivateListNode Findmiddle (ListNode head) {if(Head = =NULL|| Head.next = =NULL) { returnHead; } ListNode Slow= Head, fast =Head; while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; } returnslow; } PrivateListNode Reverse (listnode head) {//Iteration if(Head = =NULL|| Head.next = =NULL) { returnHead; } ListNode Pre=NULL; ListNode cur=Head; while(cur! =NULL) {ListNode next=Cur.next; Cur.next=Pre; Pre=cur; Cur=Next; } returnPre; } Private voidMerge (ListNode one, ListNode) { while(Both! =NULL) {ListNode next1=One.next; ListNode next2=Two.next; One.next=both ; Two.next=Next1; One=Next1; both=next2; } }}
Leetcode 143. Reorder List