141. Linked List Cycle & 142. Linked List Cycle II
来源:互联网 发布:广场舞短袖上衣淘宝网 编辑:程序博客网 时间:2024/05/02 01:35
步骤1:判定是否有环
- 慢指针sp,每次前进一步
- 快指针fp,每次前进两步
- 如果慢指针与快指针在前进n次之后指向相同的位置,则存在环;
- 否则,如果fp->next为NULL或fp->next->next为NULL,则不存在环。
步骤2:如果存在环,返回环的入口结点
设链表的头结点为X,还的入口结点为Y,快慢指针第一次相遇的点为Z。XY之间的长度为a,YZ之间的长度为b,ZY之间的长度为c。
第一次相遇时,sp走过的距离是a+b,fp走过的距离是a+b+c+b。
因为fp的速度是sp的两倍,所以2*(a+b)=a+b+c+b,即a=c。
- 所以环的长度L=b+c=a+b,也就是说环的长度就是两个指针相遇时,慢指针走过的距离。
- 前文看到a=c,所以让两个指针分别从X和Z开始走,每次都走一步,则当二者相遇时,可以得到环的入口结点Y。
class Solution {public: ListNode* EntryNodeOfLoop(ListNode* pHead) { ListNode *entryP = NULL; if(!pHead || !pHead->next || !pHead->next->next) return entryP; ListNode *sp = pHead; ListNode *fp = pHead; while(sp && fp) { sp = sp->next; if(!fp->next || !fp->next->next) break; fp = fp->next->next; if(sp == fp) { fp = pHead; while(sp!=fp) { sp = sp->next; fp = fp->next; } entryP = fp; break; } } return entryP; }};
关于本题,一个不错的博客
0 0
- 141. Linked List Cycle & 142. Linked List Cycle II
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- 141. Linked List Cycle&142. Linked List Cycle II
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- Linked List Cycle II Linked List Cycle
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- 142. Linked List Cycle II
- .NET中的范型与集合
- windows下配置mysql集群
- 在Linux下基于Eclipse的Hadoop应用开发环境配置
- Linux Shell 基本语法
- 删除oracle表空间,导致oracle启动不了
- 141. Linked List Cycle & 142. Linked List Cycle II
- Android面试(三)(转)
- 沙盒(sandbox) 及 NSFileManager
- C++ cin.getline()函数的使用
- 人脸图像数据库(完整版)
- Linux Shell 编程语法
- Android 网络请求json数据,解析json数据,生成对应的java bean类一步到位,快速开发
- 程序在别的机器上无法运行的问题
- Android Studio的library项目依赖,Jar包,常用快捷键的对比