Linked List Cycle II (LeetCode)
来源:互联网 发布:有声听书吧 软件 编辑:程序博客网 时间:2024/05/09 21:28
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
思路:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
思路:
定义两个指针:fast和slow, fast每次走两步,slow每次走一步,如果不包含循环链表,那么fast最终走向链表尾端,即以NULL结束,如果包含循环链表,那么fast和slow一定会在某个节点处相遇,并且相遇时,slow还是在第一圈,而fast在第二圈,示意图如下:
当两指针相遇的时候,fast指针所走的路程为AB+BC+CB+BC, 而slow所走的路程为AB+BC,由于fast每次移动的步数是slow的两倍,所以两者走的路程也成两倍关系:AB+BC+CB+BC = 2*(AB+BC), 即有AB = CB,所以当两者相遇后,要找到循环起始点,只需要另外定义一个指针 p 指向 head, slow指针指向相遇点,然后两者同时等步长移动,直到两者指向同一位置,指向的同一位置即为需要返回的循环起始节点。
C++解答:
class Solution {public: ListNode *detectCycle(ListNode *head) { // 如果包含循环链表,其快慢指针总会有相遇的时刻,快指针走第二圈的时候和慢指针相遇,此时慢指针还在第一圈 if(head == NULL || head->next == NULL) return NULL; ListNode *fast, *slow, *p1; fast = head; slow = head; p1 = head; while(fast!=NULL && fast->next!=NULL && fast->next->next!=NULL) { fast = fast->next->next; slow = slow->next; if(fast == slow) { while(p1!=slow) { p1 = p1->next; slow = slow->next; } return p1; } } return NULL; }};
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Kinect SDK——Face Tracking
- 关于转基因食品
- POJ 1887 Testing the CATCHER
- Freeradius+Mysql实现用户认证
- PHP中的类是如何使用魔术方法的
- Linked List Cycle II (LeetCode)
- Javascript跳转页面和打开新窗口等方法
- POJ2185--KMP最小覆盖串
- js获取虚拟目录路径
- 百度经纬度和google经纬度互转
- 段错误
- ios 静态库创建
- 有点烦
- C# 用回溯递归解决“八皇后”问题