Problem: 142. 环形链表 II
文章目录
- 思路
- Code
思路
👨🏫 参考题解
Code
⏰ 时间复杂度: O ( n ) O(n) O(n)
🌎 空间复杂度: O ( 1 ) O(1) O(1)
/**
/*** 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 f = head;ListNode s = head;while (f != null && f.next != null){f = f.next.next;s = s.next;if (f == s)// 到相遇点了{while (s != head)//两者相等即走到了入环点{s = s.next;// s 走 相遇点到入环点 的路head = head.next;// head 走 起点到入环点的路}return s;}}return null;}
}