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}
.
Change the list structure according to test instructions.
1. Use list to record linked list.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { Public voidreorderlist (ListNode head) {List<ListNode> list =NewArraylist<listnode>(); ListNode node=Head; while(Node! =NULL) {List.add (node); Node=Node.next; } intLen =list.size (); if(Len < 3) return ; Node=Head; Node.next= List.get (len-1); Node=Node.next; for(inti = 1;i<len/2;i++) {Node.next=List.get (i); Node.next.next= List.get (len-1-i); Node=Node.next.next; } if(len%2! = 0) {Node.next= List.get (LEN/2); Node=Node.next; } Node.next=NULL; return ; }}
2, use two-way queue.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { Public voidreorderlist (ListNode head) {Deque<ListNode> deque =NewArraydeque<listnode>(); ListNode node=Head; while(Node! =NULL) {Deque.add (node); Node=Node.next; } if(Deque.size () < 3) return ; Node=Deque.poll (); Node.next=Deque.polllast (); Node=Node.next; while( !Deque.isempty ()) {Node.next=Deque.poll (); Node.next.next=Deque.polllast (); Node=Node.next.next; } if(Node! =NULL) Node.next=NULL; return ; }}
3, do not use extra space, find the middle point, and then reverse the second half of the list, and then merge the two linked list.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution { Public voidreorderlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL|| Head.next.next = =NULL ) return ; ListNode Slow=Head; ListNode Fast=Head.next; while(fast!=NULL&& Fast.next! =NULL) {Fast=Fast.next.next; Slow=Slow.next; } ListNode Node2=slow; Fast=Slow.next; while(Fast! =NULL) {listnode node=Fast.next; Fast.next=slow; Slow=Fast; Fast=node; } Node2.next=NULL; Node2=slow; ListNode Node1=Head; while(Node1! =NULL) {listnode node=Node1.next; ListNode nn=Node2.next; Node1.next=Node2; Node2.next=node; Node1=node; Node2=nn; } return ; }}
Leetcode 143. Reorder List-----java