Reorder-list Topic Description
Given a singly linked list l:l0→l1→ ... →LN-1→LN, reorder it to:l0→ln→l1→ln-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}.
Ideas
- According to test instructions, a linked list is inserted from the back to the front of the past to insert the linked list, you can divide the list into two parts: the front of the binate back, the latter part from the forward, so that the latter part of the "stack" of the storage structure
- Want to use a two-step number of different pointers to divide the list into two parts, so that the results according to the list of nodes of the odd and even different, the number of linked list is less than equal to the previous. Then use the stack to store the linked list, and then traverse the previous list to insert the node.
Code
Import java.util.arraydeque;/** * DefinitionFor singly-linked list. *Class ListNode {*int Val; * ListNodeNext * ListNode (int x) {* val = x; *Next =Null * } * } */PublicClass Solution {public void Reorderlist (ListNode head) {if (head = =null | | Head.Next = =NULL) {return;} arraydeque<listnode> stack =New Arraydeque<listnode> (); ListNode pre = head; ListNode follow = head.Nextwhile (follow.Next! =null) {pre = pre. next;follow = follow. next; if (Follow. Next! = null) {follow = Follow. Next;}} Follow = Pre. next;pre. next = null;pre = Head; while (Follow! = null) {Stack.push (follow); follow = Follow. Next;} while (!stack. IsEmpty ()) {ListNode temp = Stack.pop (); Temp. Next = Pre. next;pre. next = Temp;pre = temp. next;} }}
Reorder-list-leetcode