Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
Code:
<span style="font-size:14px;">/**
* 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 == NULL || head->next == NULL || head->next->next == NULL) return;
ListNode *fast = head->next, *slow = head, *nextNode;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow->next;
slow->next = NULL;
slow = fast;
fast = fast->next;
slow->next = NULL;
while (fast != NULL) {
nextNode = fast->next;
fast->next = slow;
slow = fast;
fast = nextNode;
}
fast = head;
while (slow != NULL) {
nextNode = fast->next;
fast->next = slow;
fast = slow->next;
slow->next = nextNode;
slow = fast;
fast = nextNode;
}
return;
}
};</span>