Linked List Cycle
来源:互联网 发布:linux 重装samba 编辑:程序博客网 时间:2024/05/27 06:53
Linked List Cycle
Problem
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目
判断一个给定的链表中是否有环。
提示:在不使用额外空间的存储空间时,如何判断?
解题思路
使用两个指针,同时从链表头开始向前走,其中一个指针每次走一步,另一个指针每次走两步。若不存在环,则快指针会走到链表末端;若链表中有环,则经过若干步之后,快指针会追上慢指针。
1. 如下图所示,假设链表长度为8且不存在环,红色指针每次走两步,橘黄色指针每次走一步。则4次之后红色指针到达链表尾。
2. 如下图所示,假设链表长度为8且不存在环,红色指针每次走两步,橘黄色指针每次走一步。则红色指针经过6步之后追上橘黄色指针。此时,红色指针走的距离是橘黄色指针的两倍,且多走的距离刚好是环的长度。
代码(C++)
class Solution {public: bool hasCycle(ListNode *head) { if (!head || !(head->next)) return false; ListNode* slow = head; ListNode* fast = head; while(fast && fast->next){ fast = fast->next->next; slow = slow->next; if(slow == fast){ return true; } } return false; }};
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- LeetCode | Linked List Cycle
- 1.2.4 Selecting a defualt database
- 2016科目三满分通过,经验分享!
- 腾讯新闻中心首页改版啦
- 第10、11周项目3-警察与厨师(3)
- C++类内存实验(一)
- Linked List Cycle
- ex2_2 different presentation of a surface in 3D
- CodeIgniter框架集成微信扫码支付SDK
- mysql共享表空间转化为独立表空间
- myeclipse常快捷键
- Handler 工作机制
- Spring3整合Quartz2实现定时任务及动态任务调整(添加删除暂停恢复)--推荐
- 关于gradle编译时'your_jdk_path\bin\java.exe'' finished with non-zero exit value 2
- AlertDialog