Reorder List
Original question link Reorder List
It is required to reorder the linked list. As can be seen from the picture example, the rule is to take one from the beginning, one from the end, one from the beginning, one from the end , go on like this
Since the nodes are taken from two different places each time, the original linked list can be divided into two linked lists from the middle. One is from the header of the original chain to the middle node, and the other is from the tail of the original linked list to the middle node. In this way, you only need to take one from the first list, and then one from the second list, and repeat
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 of the list */
/* while(runner && runner->next)It is the same as the method of this question when the nodes of the linked list are odd
* When there are even numbers, the lower method will find the left side of the middle, and the upper method will find the right side of the middle */
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;
}
};