LeetCode 142. Linked List Cycle II
来源:互联网 发布:网页数据采集器 编辑:程序博客网 时间:2024/06/05 16:23
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
题目内容:
给出一个链表头指针,如果这个链表存在环路,那么找出环路入口节点,并返回这个节点,否则返回NULL。
解题思路:
这个题目是在LeetCode 141. Linked List Cycle的基础上的扩展。所以可以先参考上述连接的方法二来判断是否存在环路,方法二是一种基于追赶的思想,用2个指针slow和fast,slow每次走1个节点,fast每次走2个节点。如果存在环路,当两个指针都进入了环路之后,因为fast每次都比slow多走1个节点,所以每走一次,从fast到slow的距离会越来越小(fast在追赶slow),所以他们总会相遇。所以当slow和fast相遇,那么可以判定存在环路。
那么下一步就是找出环路的入口,首先我们定义以下一些变量:
Sslow:相遇的时候slow走的路程
Sfast:相遇的时候fast走的路程
C:环路的长度(如果存在的话)
L1:从首节点到环路入口的距离(如果存在的话)
L2:从环路如果到相遇点的距离
N:当fast和slow相遇的时候,fast在环路中已走的圈数
显然:
Sslow=L1+L2
Sfast=L1+L2+N∗C
因为fast每次走2个节点,slow每次走2个节点,那么:
2∗Sslow=Sfast
⇒2∗L1+2∗L2=L1+L2+N∗C
⇒L1+L2=N∗C
⇒L1=(C−L2)+(N−1)∗C,公式1
如下图:
因为在fast和slow相遇之前,fast至少已经在环路里走了一圈,所以
所以当我们用一开始提到的方法找到相遇节点之后,再分别用2个指针从相遇节点和起始节点出发,2个指针每次都只走1个节点,当这2个指针同时访问到同一个节点的时候,那么这个节点就是相遇点。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *detectCycle(ListNode *head) { ListNode* fast = head; ListNode* slow = head; if (head == NULL) return NULL; while (true) { fast = fast->next; if (fast == NULL) return NULL; fast = fast->next; if (fast == NULL) return NULL; slow = slow->next; if (slow == fast) break; } ListNode* current = head; while (slow != current) { slow = slow->next; current = current->next; } return slow; }};
- [LeetCode]141. Linked List Cycle【&142. Linked List Cycle II】
- leetcode--141. Linked List Cycle&&142. Linked List Cycle II
- LeetCode 141. Linked List Cycle && 142. Linked List Cycle II
- 142. Linked List Cycle II leetcode list
- LeetCode 142. Linked List Cycle II
- [LeetCode]142.Linked List Cycle II
- [leetcode] 142.Linked List Cycle II
- [leetcode] 142. Linked List Cycle II
- leetcode 142. Linked List Cycle II
- [Leetcode]142. Linked List Cycle II @python
- [LeetCode]142. Linked List Cycle II
- 142. Linked List Cycle II LeetCode
- LeetCode:142. Linked List Cycle II
- LeetCode--142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- LeetCode *** 142. Linked List Cycle II
- LeetCode 142. Linked List Cycle II
- 学习【OpenCV入门教程之十四】OpenCV霍夫变换:霍夫线变换,霍夫圆变换合辑---笔记
- 谷歌微软等科技巨头数据科学面试107道真题:你能答出多少?
- dokuwiki 居然不知道php5.6
- UVa 10934 (主要是思路)
- [网络]Unity中Http访问和下载
- LeetCode 142. Linked List Cycle II
- 04、vue.js 之绑定事件
- phlacon工具安装到phpstorm
- LinQ基本使用:查询数组
- chmod命令详细用法
- VS2017远程调试
- mousearea主要用于响应鼠标的操作,在这里我们要实现的是窗体的拖动
- iOS完整的证书申请和打包过程
- 关于在文件开头添加一行内容的Java编程