首页 > 代码库 > reorder-list——链表、快慢指针、逆转链表、链表合并

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.

 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void reorderList(ListNode *head) {
12         if(head==NULL)
13             return;
14 ListNode *slow=head,*fast=head;//快慢指针找中点 15 while(fast->next!=NULL&&fast->next->next!=NULL){ 16 fast=fast->next->next; 17 slow=slow->next; 18 } 19 20 ListNode *head1=slow->next;//逆转后半链表 21 ListNode *left=NULL; 22 ListNode *right=head1; 23 while(right!=NULL){ 24 ListNode *tmp=right->next; 25 right->next=left; 26 left=right; 27 right=tmp; 28 } 29 head1=left; 30 31 merge(head,head1);//合并两个链表 32 } 33 void merge(ListNode *left, ListNode *right){ 34 ListNode *p=left,*q=right; 35 while(q!=NULL&&p!=NULL){ 36 ListNode * nxtleft=p->next; 37 ListNode * nxtright=q->next; 38 p->next=q; 39 q->next=nxtleft; 40 p=nxtleft; 41 q=nxtright; 42 } 43 } 44 };

 

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