Given a singly linked list l: l0 → L1 →... → Ln-1 → ln,
Reorder it to: l0 → ln → L1 → Ln-1 → L2 → Ln-2 →...
You must do this in-place without altering the nodes 'values.
For example,
Given{1,2,3,4}, Reorder it{1,4,2,3}.
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
Question]
Given a linked list, insert the last node to 1st nodes, insert the last and second nodes to 2nd nodes, insert the last and third nodes to 3rd nodes, and so on ......
[Idea]
From the meaning of the question, the following (n-1)/two nodes need to be inserted to the Front (n-1)/two nodes respectively.
The linked list is divided into two sections. The first N-(n-1)/two nodes are inserted into the linked list, and the last N-(n-1)/two nodes are inserted into the linked list.
Before inserting, you need to sort the inserted linked list in reverse order, that is, the nth node-> the n-1 node->...
[Java code]
Public class solution {public void reorderlist (listnode head) {listnode node = head; int CNT = 0; while (node! = NULL) {CNT ++; node = node. next;} If (CNT <3) return; // knots below 3 do not need to move int K = (CNT-1)/2; // The last K nodes to be moved: int I = 1; node = head; while (I ++ <CNT-k) {node = node. next;} listnode begin = node. next; // use begin to indicate the Start Node of the last K nodes to be moved. next = NULL; // set the end of the part that does not need to be moved to null. // set the K nodes to be moved to the reverse order of listnode pre = begin; listnode cur = begin. next; begin. next = NULL; while (cur! = NULL) {listnode next = cur. next; cur. next = pre; begin = cur; Pre = cur; cur = next;} listnode node1 = head; listnode node2 = begin; while (node1! = NULL & node2! = NULL) {pre = node1; cur = node2; node1 = node1.next; // these two rows must be placed before the following two rows, because pre and node1 point to the same node, the following operation will change the next of node1. The same reason is node2 = node2.next and cur. next = pre. next; // these two lines of code insert cur into pre-post-pre. next = cur ;}}}
[Feelings]
The code is too disgusting to write, and it will be confusing to write it. Later, I will not know which node next refers.
[Leetcode] reorder list