143. Reorder List
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.
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
|
class Solution { public: void reorderList(ListNode* head) { vector<ListNode*> nodes; while(head) { nodes.push_back(head); head = head->next; } int l = 0, r = nodes.size() - 1; while(l <= r) { nodes[l++]->next = nodes[r]; if(l < r) nodes[r--]->next = nodes[l]; else nodes[r]->next = nullptr; } } };
|