[LeetCode]Linked List Cycle
来源:互联网 发布:input file js赋值 编辑:程序博客网 时间:2024/06/06 12:26
题目:
Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
来源:http://oj.leetcode.com/problems/linked-list-cycle/
思路:
这题目之前看到过,所以一下就出来了,用连个指针,一个一次走两步,一个一次走一步。不过思路自己说的不大清楚,参考下别人写的。
第一次相遇时slow走过的距离:a+b,fast走过的距离:a+b+c+b。
因为fast的速度是slow的两倍,所以fast走的距离是slow的两倍,有 2(a+b) = a+b+c+b,可以得到a=c(这个结论很重要!)。
我们发现L=b+c=a+b,也就是说,从一开始到二者第一次相遇,循环的次数就等于环的长度。
2. 我们已经得到了结论a=c,那么让两个指针分别从X和Z开始走,每次走一步,那么正好会在Y相遇!也就是环的第一个节点。
3. 在上一个问题的最后,将c段中Y点之前的那个节点与Y的链接切断即可。
4. 如何判断两个单链表是否有交点?先判断两个链表是否有环,如果一个有环一个没环,肯定不相交;如果两个都没有环,判断两个列表的尾部是否相等;如果两个都有环,判断一个链表上的Z点是否在另一个链表上。
如何找到第一个相交的节点?求出两个链表的长度L1,L2(如果有环,则将Y点当做尾节点来算),假设L1<L2,用两个指针分别从两个链表的头部开始走,长度为L2的链表先走(L2-L1)步,然后两个一起走,直到二者相遇。
C++ AC代码:
/** * 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 == NULL) return false;ListNode *fast = head;ListNode *slow = head;while (fast!=NULL&&fast->next!=NULL){slow = slow->next;fast = fast->next->next;if (fast==slow)return true; }return false; }};
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
- android实用代码块
- POJ 1562 Oil Deposits (简单深搜)
- 谷歌Gmail诞生记:十年回首
- 细说 ASP.NET Cache 及其高级用法
- 关于int *a; int &a; int & *a; int * &a
- [LeetCode]Linked List Cycle
- 取出对象中的字符串
- 类加载器---类加载器简介
- 堆排序
- 五子棋 - 稍微写出有点实际用途的程序了,感觉不错!
- 【LeetCode】Single Number
- WINDOWS下C++的套接字编程
- Android开发之使用SharedPreferences实现QQ登陆的选项框记忆功能(源代码分享)
- android应用开发MVC框架(一)