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}
网上最多的方法是:
用快慢指针找出中点,然后把后半段逆序,之后插入;空间ON,时间ON,遍历三遍,第一遍找出中点,第二遍逆序,第三遍插入。
还有一种方法:
先把链表入栈,之后出栈插入即可。判断结束的条件是原链表的节点的下一个或者下一个的下一个是栈顶的节点。空间ON,时间ON,遍历两遍,第一遍入栈,第二遍插入。这个我没实现。
/**
* 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) return;
ListNode* fast=head;
ListNode* slow=head;
ListNode* re=NULL;
while(fast&&fast->next){
fast=fast->next->next;
re=slow;
slow=slow->next;
}
ListNode* pre=NULL;
ListNode* p=slow;
while(p->next){
ListNode* q=p->next;
p->next=pre;
pre=p;
p=q;
}
int ok=1;
if(fast){
ok=0;
}
p->next=pre;
re->next=NULL;
ListNode* l1=head;
while(l1){
ListNode* q=l1->next;
l1->next=p;
ListNode* tmp=p->next;
if(!(ok==0&&q==NULL)){
p->next=q;
}
l1=q;
p=tmp;
}
return;
}
};