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}
.
借助栈可以实现时间复杂度为O(N),找到链表中点,那么从中点往左的每一个结点都是需要插入结点的点,而从中点往右的结点都是需要被插入到前半部分的结点。代码如下:
/**
* 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) {
stack<ListNode *> paths;
int len = length(head);
if(len<=2) return;
int repeatTimes = len%2 ? len/2:len/2-1;
int i=1;
ListNode *p=head;
while(i <= repeatTimes){
paths.push(p);
if(i!=repeatTimes)
p=p->next;
++i;
}
ListNode *pre = p;//此处的p是栈顶元素
if(len%2){//奇数的情况
pre = p->next;
}else{
pre = p->next->next;
}
p = pre->next;
while(p){
pre->next = p->next ;
if(!paths.empty()){
ListNode *q = paths.top();
p->next = q->next;
q->next = p;
paths.pop();
p = pre->next;
}
}
}
private:
int length(ListNode *head){
int len = 0 ;
while(head){
++len;
head=head->next;
}
return len;
}
};