Discription
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}
.
void reorderList(ListNode* head) {
if (!head || !head->next) return;
ListNode *pslow = head, *pfast = head->next;
while (pfast && pfast->next){
pfast = pfast->next->next;
pslow = pslow->next;
}
ListNode *cur = pslow->next;
pslow->next = NULL;
ListNode *pre = NULL;
while (cur){
ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
cur = head;
while (pre){
ListNode *tmp1 = cur->next;
ListNode *tmp2 = pre->next;
cur->next = pre;
pre->next = tmp1;
cur = tmp1;
pre = tmp2;
}
}
GitHub-Leetcode:
https://github.com/wenwu313/LeetCode