Given a singly linked list l:l0→l1→ ... →ln-1→ln
Reorder It to:l0→ln→l1→ln-1→l2→ln-2→ ...
Example
Given 1->2->3->4->null
, reorder it to 1->4->2->3->null
.
Challenge
Can do this in-place without altering the nodes ' values?
/*** Definition for ListNode. * public class ListNode {* int val; * ListNode Next; * ListNode (int val) {* This.val = val; * This.next = null; * } * } */ Public classSolution {/** * @paramhead:the head of linked list. * @return: void*/ Public voidreorderlist (ListNode head) {//Write your code here if(Head = =NULL|| Head.next = =NULL|| Head.next.next = =NULL) return; ListNode Slow=Head; ListNode Fast=Head; while(Fast! =NULL&& Fast.next! =NULL&& Fast.next.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; } ListNode head2=Slow.next; Slow.next=NULL; Head2=reverse (head2); ListNode P1=Head; ListNode P2=head2; ListNode P1_next=Head.next; ListNode P2_next=Head2.next; while(P1_next! =NULL&& P2_next! =NULL) {P1.next=P2; P2.next=P1_next; P1=P1_next; P2=P2_next; P1_next=P1_next.next; P2_next=P2_next.next; } P1.next=P2; P2.next=P1_next; return; } PublicListNode Reverse (listnode head) {if(Head = =NULL|| Head.next = =NULL) returnHead; ListNode prev=Head; ListNode Curr=Head.next; ListNode Next=Head.next.next; Head.next=NULL; while(Next! =NULL) {Curr.next=prev; Prev=Curr; Curr=Next; Next=Next.next; } Curr.next=prev; returnCurr; }}
Lintcode-medium-reorder List