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}
.
Solution:
Use a deque to link front and back.
Code:
/**
* 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||!head->next) return;
deque<ListNode*> queue;
ListNode *cur = head->next;
while(cur){
queue.push_back(cur);
cur = cur->next;
}
cur = head;
while(!queue.empty()){
cur->next = queue.back();
queue.pop_back();
cur = cur->next;
if(queue.empty()) break;
cur->next = queue.front();
queue.pop_front();
cur = cur->next;
}
cur->next = NULL;
return;
}
};