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}.
由于链表尾端不干净,导致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 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-06-07 TelephonyManager类与PhoneStateListener