Leetcode:Linked List Cycle 菜鸟解法
来源:互联网 发布:10月经济数据分析 编辑:程序博客网 时间:2024/06/07 16:22
这题确实没想出来,后面问了别人,别人提示了快慢指针才有所领悟。。。
对于一个链表来说,判断他是否包含环其实很简单,一直循环下去没终止肯定是包含,next的为NULL了肯定不包含
而快慢指针就像两个人跑圈,速度可能不一样,但是如果套圈了,那说明中途一定是遇到交点了,用类似的原理可以解决这个问题。
代码如下:
class Solution {public: bool hasCycle(ListNode *head) { ListNode *slow,*fast; if(head==NULL||head->next==NULL) return false; slow = head; fast = head->next; while(fast->next!=NULL){ if(fast->next==slow->next) return true; slow = slow->next; fast = fast->next->next; if(fast==NULL) return false; } return false; }};
0 0
- Leetcode:Linked List Cycle 菜鸟解法
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- CreateJS基础 学习笔记(上)
- 从头到尾彻底理解KMP
- struts的DevMode模式
- ios scrollview浅谈(入门)
- HelloBlog
- Leetcode:Linked List Cycle 菜鸟解法
- hdu 1011 Starship Troopers
- Linux如何实现开机启动程序详解
- 剪花布条
- range,xrange,arange比较
- zoj 1053 && poj 1122 FDNY to the Rescue!
- android开发之Google工程师多图详解Android架构
- poj2112 Optimal Milking
- Cocos2d-x 绘制基本图形