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}
.
Problem solving idea One:
Each time ln is changed to the front, I get l0→ln→l1→l2→L3→, Then use the same operation for L1, the Java implementation is as follows:
public void Reorderlist (ListNode head) {ListNode headcopy = head;while (headcopy! = NULL && headcopy.next! = null& amp;& HeadCopy.next.next! = null) {ListNode temp = headcopy;while (Temp.next.next! = null) temp = TEMP.NEXT;TEMP.NEXT.N ext = Headcopy.next;headcopy.next = Temp.next;temp.next = Null;temp = Headcopy.next.next;headcopy=headcopy.next.next;}}
Results tle
Two ways to solve problems:
Space change time, all of the node is stored in a list, and then each operation of the list two node, the Java implementation is as follows:
public void Reorderlist (ListNode head) {linkedlist<listnode> list = new linkedlist<listnode> (); ListNode headcopy = Head,end = Head;while (headcopy! = null) {List.add (headcopy); headcopy = Headcopy.next;} while (List.size () >2) {headcopy=list.poll (); End=list.get (List.size ()-1); List.remove (List.size ()-1); Headcopy.next=end;end.next=list.peek (); List.get (List.size ()-1). Next=null;} }
Java for Leetcode 143 Reorder List