Problem: 142. 环形链表 II
思路
快慢指针
解题方法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vcXUigI1-1679156753250)(https://pic.leetcode.cn/1679156154-ITnAfD-%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230318225431.jpg)]
复杂度
- 时间复杂度:
O ( n ) O(n) O(n)
因为slow 指针走过的距离不会超过链表的总长度
- 空间复杂度:
O ( 1 ) O(1) O(1)
Code
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
//快慢指针
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){//相遇点
ListNode index = fast;
ListNode cur = head;
while(index != cur){
index = index.next;
cur = cur.next;
}
return cur;
}
}
return null;
}
}