Reorder List
Original title Link Reorder List
Asked to reorder the linked list, there are examples of pictures you can see, the rule is to take one from the beginning, and then take one from the tail, and then take it from the end of the,..., this goes on
Since every time from two different places to pick up the node, then the original linked list from the middle to split into two linked lists, a linked list from the original linked table to the middle node, the other linked list from the original list of the table to the middle node. In this way, you only need to take one from the first list, and then take one from the second list, and repeat it.
The code is as follows
/** * Definition for singly-linked list.
* struct ListNode {* int val;
* ListNode *next;
* ListNode (int x): Val (x), Next (NULL) {} *};
* * Class Solution {public:void reorderlist (listnode* head) {if (!head | |!head->next) return;
Auto Walker = head;
Auto runner = head; /* Find the middle position of the list/* while (runner && Runner->next) and the method of the subject when the list node is an odd number of the same * even when the following method will find the middle left, the above method will find Middle right/while (runner && Runner->next && Runner->next->next) {Walker
= walker->next;
Runner = runner->next->next;
Auto Head1 = head;
Auto Head2 = walker->next;
Walker->next = nullptr;
head2 = reverse (head2);
while (Head1 && head2) {Auto Next1 = head1->next;
Auto NEXT2 = head2->next;
Head1->next = head2;
Head2->next = Next1; Head1 = Next1;
Head2 = next2;
} private:listnode* Reverse (listnode* head) {listnode* prev = nullptr;
listnode* cur = head;
while (cur) {Auto next = cur->next;
Cur->next = prev;
prev = cur;
cur = next;
return prev; }
};