Recorder List: Given a singly linked list l: l0→l1→ ... →ln-1→ln,reorder it to: l0→ln→l1→l n-1→l2→ln-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}
.
Test Instructions: given a list, the last node is inserted behind the first node, the penultimate node is inserted behind the second node of the original list, and so on.
idea: Use the fast pointer method to find the midpoint of the list, then reverse the linked list to the right of the midpoint, then merge the two linked lists.
Code:
Public voidreorderlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL)return; ListNode Slow=Head; ListNode Fast=Head; while(Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; } ListNode Mid=Slow.next; ListNode cur=mid; ListNode Pre=NULL; while(cur! =NULL) {ListNode post=Cur.next; Cur.next=Pre; Pre=Last ; Cur=Post; } Slow.next=NULL; while(Head! =NULL&& Pre! =NULL) {ListNode next1=Head.next; Head.next=Pre; Pre=Pre.next; Head.next.next=Next1; Head=Next1; } }
Leetcode (143): Recorder List