[LeetCode]Linked List Cycle II
2015-11-13 14:24
489 查看
题目链接:Linked List Cycle II
题目内容:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
题目解法:
题目要求判断链表中是否有环,如果有,要返回环的起始结点,否则返回空。这道题的关键有二,一是环的判定,二是找到环的起点。幸运的是,这两个问题都可以用双指针法解决。
双指针法
双指针法是指使用两个指针slow、fast,开始都指向头结点,接着slow每次移动一步,fast每次移动两步。
判断环
因为fast每次都比slow多走一步,当两者都进入环路时,设二者顺时针相距k,那么每次fast都比slow多走一步,一定可以在有限步数内弥补这段距离,从而相遇,因此当fast==slow时我们可以知道有环存在。
找起点
我们设slow和fast在Z点相遇,那么当相遇时,slow走过的距离为a+b,fast走过的距离为a+b+c+b,又因为fast走过的距离是slow的2倍,因此2(a+b)=a+2b+c,也就是a=c,因此在相遇时,我们把slow重新指向起点X,然后每次fast和slow都只走一步,因为a=c,当两者相遇时恰好在Y点,也就是环的起点。
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *slow; ListNode *fast; if(head == NULL || head->next == NULL || head->next->next == NULL) return NULL; slow = head->next; fast = head->next->next; while(1){ if(slow == fast) break; if(slow->next == NULL) return NULL; slow = slow->next; if(fast->next == NULL) return NULL; fast = fast->next; if(fast->next == NULL) return NULL; fast = fast->next; } fast = head; while(slow != fast){ slow = slow->next; fast = fast->next; } return fast; } };
参考的博客:
1.sysucph,Linked List Cycle II2.小虫不会飞_,LeetCode:Linked List Cycle && Linked List Cycle II
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- [C/C++]反转链表
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 动易2006序列号破解算法公布
- C#实现基于链表的内存记事本实例
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C++联合体转换成C#结构的实现方法
- C#实现的算24点游戏算法实例分析
- C++编写简单的打靶游戏