Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
/**
* 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) {
if (head == null || head.next == null || head.next.next == null) {
return null;
}
ListNode n1 = head.next;
ListNode n2 = head.next.next;
while (n1 != n2) {
if (n2.next == null || n2.next.next == null) {
return null;
}
n1 = n1.next;
n2 = n2.next.next;
}
n2 = head;
while (n1 != n2) {
n1 = n1.next;
n2 = n2.next;
}
return n1;
}
}
本文介绍了一种高效算法来检测链表中是否存在循环,并找到循环开始的节点。通过两个指针快慢移动的方式,当两者相遇时,再从头结点与相遇点同步移动直至再次相遇即为循环起点。
454

被折叠的 条评论
为什么被折叠?



