Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?node
给定一个单链表,若是它有环,返回环入口的第一个节点,不然返回null算法
先判断链表是否有环,使用快(fast)慢指针(slow),解法见单链表中有环,若是没有环就返回null,若是有环,有fast=slow,就让让slow从新指向链表头,而后两个指针每次同时移动一个位置,直到两链表相遇,相遇点就是环的入口结点。spa
结点类.net
class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } }
算法实现类指针
public class Solution { public ListNode detectCycle(ListNode head) { 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; } slow = head; while (fast != slow) { fast = fast.next; slow = slow.next; } return slow; } }