题目链接
环路检测
题目描述
注意点
- 返回环路的开头节点
解答思路
- 快慢指针确认链表中是否有环,如果无环则快指针最终会到达链表尾部,如果有环则快慢指针会相遇,当快慢指针相遇,此时新的节点node从head开始出发,与slow一样每次移动一格,直到node与slow相遇,此时的node就是环路的开头节点
代码
/**
* 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 slow = head;
ListNode quick = head;
while (quick != null && quick.next != null) {
slow = slow.next;
quick = quick.next.next;
if (slow == quick) {
break;
}
}
if (quick == null || quick.next == null) {
return null;
}
ListNode node = head;
while (slow != node) {
slow = slow.next;
node = node.next;
}
return node;
}
}
关键点
- 无