LeetCode 143. 重排链表

题目链接:https://leetcode-cn.com/problems/reorder-list/

给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

小结:感觉这题比较好,虽然题目简单也易理解,但是有很多常规操作,先是快慢指针,其次是逆置链表,最后是俩链表的合并。

 1 void reorderList(struct ListNode* head){
 2     if(head==NULL||head->next==NULL) return head;
 3     struct ListNode *slow=head,*fast=head,*q,*p,*head1,*head2;
 4     while(fast->next&&fast->next->next){
 5         slow=slow->next;
 6         fast=fast->next->next;
 7     }
 8     head1=head;
 9     head2=slow->next;
10     slow->next=NULL;
11     struct ListNode *pre=NULL,*cur=head2,*tmp;
12     while(cur){
13         tmp=cur->next;
14         cur->next=pre;
15         pre=cur;
16         cur=tmp;
17     }
18     head2=pre;
19     q=head1,p=head2;
20     struct ListNode *new=(struct ListNode*)malloc(sizeof(struct ListNode));
21     cur=new;
22     while(q&&p){
23         cur->next=q;
24         q=q->next;
25         cur=cur->next;
26         cur->next=p;
27         p=p->next;
28         cur=cur->next;
29     }
30     if(q) cur->next=q;
31     return new->next;
32 }

 

posted @ 2020-03-06 11:39  wydxry  阅读(235)  评论(0编辑  收藏  举报
Live2D