Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
/* 交错链表
* 1 2 3 4 5 6
* 1 2 3|4 5 6
* 1 2 3|6 5 4
* 1 6 2 5 3 4
*
* 1 2 3 4 5
* 1 2 3| 4 5
* 终点拆分 如果是奇数 保证前面比后面多 后面部分逆序后依次插入
* */
class Solution {
public:
void reorderList(ListNode* head) {
ListNode *left=new ListNode(-1), *right=new ListNode(-1), *p=left, *fast=left;
left->next = head;
// eg: 1 3 5 p指向3 p->next 为rightpart
while(fast&&fast->next){
p = p->next;
fast = fast->next->next;
}
//cout<<p->val<<endl;
right->next = p->next;
p->next = NULL; //重要 不然等下left链表的尾部还是right
ListNode *tmp = right->next, *tmpnext;
right->next=NULL;// 重要 要先把头结点拿下来!!不然进行头插时 头结点的后继节点不为空
while(tmp){
tmpnext = tmp->next;
tmp->next = right->next;
right->next = tmp;
tmp = tmpnext;
}
//cout<<right->next->val<<endl;
ListNode *l=left->next, *r=right->next, *lnext, *rnext;
while(r){
lnext = l->next;rnext = r->next;
//cout<<l->val<<" "<<r->val<<endl;
r->next = lnext;
l->next = r;
r = rnext; l = lnext;
}
}
};