示例#1
0
        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 != slow)
            {
                return(null);
            }

            //x + y = n (y + z)
            // n=1  x=z

            //set fastpoint to head
            //exsit cycle
            fast = head;

            while (fast != slow)
            {
                fast = fast.next;
                slow = slow.next;
            }

            return(fast);
        }
示例#2
0
 public ListNode(int x)
 {
     val  = x;
     next = null;
 }