reorder-list——链表、快慢指针、逆转链表、链表合并

时间:2023-03-09 00:16:08
reorder-list——链表、快慢指针、逆转链表、链表合并

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}.

由于链表尾端不干净,导致fast->next!=NULL&&fast->next->next!=NULL判断时仍旧进入循环,此时fast为野指针

1 /** 2 * 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)
return;
ListNode *slow=head,*fast=head;//快慢指针找中点
while(fast->next!=NULL&&fast->next->next!=NULL){
fast=fast->next->next;
slow=slow->next;
} ListNode *head1=slow->next;//逆转后半链表
ListNode *left=NULL;
ListNode *right=head1;
while(right!=NULL){
ListNode *tmp=right->next;
right->next=left;
left=right;
right=tmp;
}
head1=left; merge(head,head1);//合并两个链表
}
void merge(ListNode *left, ListNode *right){
ListNode *p=left,*q=right;
while(q!=NULL&&p!=NULL){
ListNode * nxtleft=p->next;
ListNode * nxtright=q->next;
p->next=q;
q->next=nxtleft;
p=nxtleft;
q=nxtright;
}
}
};