# 143. Reorder List
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
# Solution
Approach 1: Iterate the list.
# Code (Python)
Approach 1:
# Code (C++)
Approach 1:
/**
* 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) {
// Reach the middle of the list.
ListNode *slow = head;
ListNode *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
// Reverse the last half of the list.
ListNode *prev = slow;
while (slow)
{
ListNode *next = slow->next;
slow->next = prev;
prev = slow;
slow = next;
}
// Reorder the list.
ListNode *tail = prev;
ListNode dummyHead(0);
dummyHead.next = head;
ListNode *curr = &dummyHead;
while (head != tail)
{
curr->next = head;
head = head->next;
curr = curr->next;
curr->next = tail;
tail = tail->next;
curr = curr->next;
}
curr->next = head;
curr = curr->next;
if (curr)
curr->next = NULL;
}
};