143. Reorder List

143. Reorder List

Description

Difficulty: Medium

Related Topics: Linked List, Two Pointers, Stack, Recursion

You are given the head of a singly linked-list. The list can be represented as:

1
L0 → L1 → … → Ln - 1 → Ln

Reorder the list to be on the following form:

1
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:

1
2
Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:

1
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 * 104].
  • 1 <= Node.val <= 1000

Hints/Notes

Solution

Iterative solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* 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:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}

ListNode* reverseList(ListNode* head) {
ListNode *cur = head, *prev = nullptr;
while (cur) {
ListNode* nxt = cur->next;
cur->next = prev;
prev = cur;
cur = nxt;
}
return prev;
}

void reorderList(ListNode* head) {
// get the pointer to the middle node, e.g. 1, 2, 3, return pointer to 2
ListNode* mid = middleNode(head);
// two cases:
// #1:
// 1 -> 2
// 3 -> 2
// #2:
// 1 -> 2 -> 3
// 4 -> 3
mid = reverseList(mid);
while (mid->next) {
ListNode* nxt1 = head->next;
ListNode* nxt2 = mid->next;
head->next = mid;
mid->next = nxt1;
head = nxt1;
mid = nxt2;
}
}
};

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * 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) {
stack<ListNode*> s;
ListNode* tmp = head;
while (tmp) {
s.push(tmp);
tmp = tmp->next;
}
tmp = head;
while (tmp != s.top() && tmp->next != s.top()) {
ListNode* tail = s.top();
s.pop();
ListNode* next = tmp->next;
tmp->next = tail;
tail->next = next;
tmp = next;
}
if (tmp == s.top()) {
tmp->next = nullptr;
} else {
tmp->next->next = nullptr;
}
}
};