Difficulty: Medium
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}
.
/**
* 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)
return ;
deque<ListNode*> que;
ListNode *p=head;
while(p){
que.push_back(p);
p=p->next;
}
head=new ListNode(-1);
p=head;
while(!que.empty()){
ListNode *t1=que.front();
ListNode *t2=nullptr;
que.pop_front();
if(!que.empty()){
t2=que.back();
que.pop_back();
}
p->next=t1;
p=p->next;
p->next=t2;
p=p->next;
}
if(p)
p->next=nullptr;
p=head;
head=head->next;
free(p);
}
};