141. Linked List Cycle&142. Linked List Cycle II
来源:互联网 发布:王者荣耀开黑连麦软件 编辑:程序博客网 时间:2024/05/09 09:47
Given a linked list, determine if it has a cycle in it.
class Solution {public: bool hasCycle(ListNode *head) { if(head==NULL) return 0; ListNode *fast=head; ListNode *slow=head; while(fast->next&&fast->next->next){ fast=fast->next->next; slow=slow->next; if(fast==slow) return 1; } return 0; }};
值得注意的是一开始会疑惑为什么while的check条件要检查fast->next和fast->next->next,而不是检查slow,后来想通了,因为fast走得比slow快,如果链表没有循环的话,fast会更快走到NULL的地方。因此需要进行检查。
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
这题有个链接讲得很好:http://blog.csdn.net/u014248312/article/details/51712554
class Solution {public: ListNode *detectCycle(ListNode *head) { if(head==NULL) return NULL; ListNode *fast=head; ListNode *slow=head; while(fast->next&&fast->next->next){ fast=fast->next->next; slow=slow->next; if(fast==slow){ slow=head; while(fast!=slow){ slow=slow->next; fast=fast->next; } return fast; } } return NULL; }};
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
- IDEA 快捷键。Linux/Windows及mac下的对照
- 2017新年规划
- 数据结构与算法JavaScript描述[第六章](链表)
- Java isAssignableFrom、instanceof 、isInstance
- Lab 色彩空间
- 141. Linked List Cycle&142. Linked List Cycle II
- java垃圾回收
- ubuntu下安装flash
- 欢迎使用CSDN-markdown编辑器
- [洛谷p2014]选课
- C++之类
- 视音频数据处理入门:RGB、YUV像素数据处理
- 线程池
- HDU 1518 Square(DFS)