[Leetcode] 141. Linked List Cycle 解题报告
来源:互联网 发布:mysql重置root密码 编辑:程序博客网 时间:2024/04/29 20:25
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:
这个题目估计已经被问烂了,玩坏了。所以真正面试的时候估计一般不会考。不过里面two pointers的思路倒是解决链表问题的神器之一。我们定义快慢指针,慢的一次走一步,快的一次走两步。如果相遇,则有环,否则无环。时间复杂度O(n),空间复杂度O(1),其中n是链表的长度。
代码:
/** * 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) { if (!head) { return false; } ListNode *slow = head, *fast = head; while (fast->next && fast->next->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { return true; } } return false; }};
0 0
- [leetcode] 141. Linked List Cycle 解题报告
- [Leetcode] 141. Linked List Cycle 解题报告
- LeetCode — Linked List Cycle 解题报告
- [LeetCode OJ] Linked List Cycle 解题报告
- 【LeetCode】Linked List Cycle 解题报告
- [leetcode]141. Linked List Cycle@Java解题报告
- 【LeetCode】141.Linked List Cycle(easy)解题报告
- LeetCode — Linked List Cycle II 解题报告
- [LeetCode OJ] Linked List Cycle II 解题报告
- [leetcode] 142. Linked List Cycle II 解题报告
- [Leetcode] 142. Linked List Cycle II 解题报告
- [leetcode]142. Linked List Cycle II@Java解题报告
- LeetCode---Linked List Cycle、Linked List Cycle II解题分析
- leetCode Linked List Cycle 解题分享
- [LeetCode]141.Linked List Cycle
- LeetCode 141. Linked List Cycle
- [Leetcode] 141. Linked List Cycle
- LeetCode 141. Linked List Cycle
- Ehcache(05)——缓存的查询
- Android-Fragment 中 嵌套 ViewPager 结构,ViewPager 中的Fragment再次可见的时候 出现空白
- Android SettingProvider详解
- 原生上传文件
- Matlab时频分析工具箱小波尺度图函数的使用说明与实例
- [Leetcode] 141. Linked List Cycle 解题报告
- 关于去掉tableViewCell 多余分割线
- elasticsearch rest api操作
- Nginx隐藏软件版本号信息
- 同一服务器中多开 tomcat
- HDU 6031 Innumerable Ancestors (LCA)
- Android 中处理POWER/HOME流程
- JS事件--事件处理程序之HTML事件处理程序
- 目标跟踪方法的发展概述