【Leetcode】Linked List Cycle
来源:互联网 发布:sql数据库获取当前时间 编辑:程序博客网 时间:2024/06/05 04:46
题目要求:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool hasCycle(ListNode *head) { }};
解题方法:
fast and slow runner。
在一个环形跑道中,有两个不知疲倦的人在跑步。可以肯定的是,跑的快的人,一定会追上跑的慢的人。这也可以用在这里判断链表是否有环。
两个节点a,b。a每次走两步,b每次只走一步。如果链表有环,那么a一定会赶上b。
code:
class Solution {public: bool hasCycle(ListNode *head) { ListNode *slow, *fast; slow = fast = head; if(head==NULL) return false; while(slow && fast && fast->next) { slow = slow->next; fast = fast->next->next; //注意,如果fast在这里可能已经为空,所以在循环中加上判断 if(slow == fast) return true; } return false; }};
尊重知识的来源: Does everyone solved it with O(n) complexity?
0 0
- 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
- Linked List Cycle -- LeetCode
- iOS_31_cocos2d_CCScene
- zoj 1002 Fire Net (简单dfs)
- 二叉树的三叉链表存储(java实现)
- 借助JavaCV实现android手机查看PC摄像头实时视频
- c++11特性与cocos2d-x 3.0之std::bind与std::function
- 【Leetcode】Linked List Cycle
- 软工视频——1-3章总结
- Command line option syntax error.type Command /? for help
- java内存模型
- 正态分布的前世今生
- 正则表达式总结
- 调试内核:去掉优化选项
- Service结合通知下载图片
- 【android】app中实现时间展示样式