143. Reorder List
Description of Problem
You are given the head of a singly linked-list. The list can be represented as:
L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [1,4,2,3]
Example 2:
Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]
Constraints:
- The number of nodes in the list is in the range
[1, 5 * 10^4]. 1 <= Node.val <= 1000
Solution
Tags: LinkedList
Explanation
Simply speaking, find the middle node using fast and slow pointers, cut the list into two lists, reverse the latter and combine them.
Code (C++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
// 1. Find the middle node
while(fast->next != nullptr && fast->next->next != nullptr){
slow = slow->next;
fast = fast->next->next;
}
// 2. Cut and Reverse
ListNode* curr = slow->next;
ListNode* prev = nullptr;
slow->next = nullptr; // Cut
// Reverse
while(curr != nullptr){
ListNode* temp = curr;
curr = temp->next;
temp->next = prev;
prev = temp;
}
// 3. Merge
ListNode* list1 = head; ListNode* list2 = prev;
while(list1 != nullptr && list2 != nullptr){
ListNode* temp1 = list1->next;
ListNode* temp2 = list2->next;
list1->next = list2;
list2->next = temp1;
list1 = temp1;
list2 = temp2;
}
}
};
Complexity
Time Complexity:
- \(T(n)=O(n)\)
- There are only nearly constant number of n iterations
Auxiliary Space:
- \(S(n)=O(1)\)
- Use only constant number of variables