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(null==head) return null;
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
break;
}
}
if(fast==null||fast.next==null){
return null;
}
fast=head;
while(fast!=slow){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
本文介绍了一种高效算法来解决链表中循环起点的查找问题。通过使用快慢指针技巧,可以在O(n)时间内找到循环开始的节点,如果链表不存在循环则返回null。
552

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



