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}
.
The subject can be seen as the further complex state of reverse Linked List 2, the problem-solving idea is
If the list is 1 2 3 4 5 6 7 8 9
1. Find the middle element of the list
2. Reverse the second half of the list (using reverse Linked the concept of List 2)
3. New Linked List 1 2 3 4 5 9 8 7 6. The list is reordered (also using reverse Linked List 2, the elements in the second half of the list are inserted one by one into the first half, 9 inserted between 1, 2, 8 inserted between 2, 3 ...). )
When solving a problem, a long time debug is performed due to the loss of the moving bit
Therefore, it should be noted that
1. If you remove one of the linked lists, you must save the
2. If one of the linked lists is added, save the next one
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int x) {val = x;}}} */public class Soluti On {public void reorderlist (ListNode head) {if (head==null| | Head.next==null) return; ListNode P1 = head; ListNode P2 = head; while (P2.next = null && p2.next.next! = null) {P1 = P1.next; P2 = p2.next.next; } listnode pre = P1; ListNode Curr = P1.next; ListNode middle = p1; while (curr.next! = null) {ListNode then = Curr.next; Curr.next = Then.next; Then.next = Pre.next; Pre.next = then; then = Curr.next; } ListNode start = head; ListNode move = Middle.next; while (start! = middle) {Middle.next = Move.next; Move.next = Start.next; Start.next = move; start = Move.next; move = Middle.next; } }}
143. Reorder List