- 描述
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
- 思路
假如允许修改链表,那么倒有一种取巧的办法,即使遍历链表,每次将链表的值赋值为该节点hash,如果有环,那么一定会有一次该节点的hashcode等于该节点的值,返回该节点即得到结果。但是题目中要求不能修改链表,上面的思路就无效,这里参考了其他博主的思路:
http://blog.csdn.net/xy010902100449/article/details/48995255 - 符合要求代码(c#)
public ListNode DetectCycle(ListNode head) {
if (head == null) return null;
var fast = head;
var slow = head;
do
{
if (fast == null) return null;
fast = fast.next;
slow = slow.next;
if (fast != null)
{
fast = fast.next;
}
else
{
return null;
}
}
while (fast != slow);
slow = head;
while (slow != fast)
{
fast = fast.next;
slow = slow.next;
}
return slow;
}
不符合要求代码(c#)
public ListNode DetectCycle(ListNode head)
{
while (head != null)
{
int key = head.GetHashCode();
if (key == head.val) return head;
head.val = key;
head = head.next;
}
return null;
}