143. Reorder List
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}
.
点击打开链接 转载出处
思路:分为3步走。
void reorderList(ListNode* head) {
if(!head||!head->next) return;
//第一步,找到链表的中间节点
ListNode* premid=NULL;
ListNode* slow=head,* fast=head;
while(fast->next && fast->next->next)
{
slow=slow->next;
fast=fast->next->next;
}
premid=slow;
//第二步,将后半部分的链表进行翻转,L1->L2->L3->L6->l5->L4
ListNode* precurr=premid->next;
while(precurr->next)
{
ListNode* curr=precurr->next;
precurr->next=curr->next;//先将要插入的点cur从原来的位置删除
curr->next=premid->next;//连接cur的后边结点
premid->next=curr;//连接cur的前面结点
}
//第三步:将两个链表合并,1->6->2->5->4->3,将后半部分的结点一个个的删除,再插入正确位置
ListNode* p1,*p2;
p1=head;
p2=premid->next;
while(p1!=premid)
{
premid->next=p2->next;//删除要改变位置的点p2,这里是结点6
p2->next=p1->next;//将p2与后面的点相连
p1->next=p2;//将p2与前面的点相连
p1=p2->next;//更新p1
p2=premid->next;//更新p2
}
}