LeetCode 142 链表 Linked List Cycle II

LeetCode 142 链表 Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

代码:

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null) return null;
        ListNode slow = head;
        ListNode fast = head;
        while(slow != null && fast != null){
            if(fast.next != null)
                fast = fast.next.next;
            else
                return null;
            slow = slow.next;
            if(fast == slow) break;
        }
        if(fast == null)
            return null;

        int circleNum = 1;
        ListNode tmp = slow.next;
        while(tmp != slow){
            tmp = tmp.next;
            circleNum++;
        }

        fast = head;
        slow = head;
        for(int i = 0; i < circleNum; i++){
            fast = fast.next;
        }
        while(fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}

注意:
在第一步找有没有环的时候别丢了相等判断,自己不要犯一些这种小错误

猜你喜欢

转载自www.cnblogs.com/muche-moqi/p/12400849.html