LeetCode 142 链表 Linked List Cycle II

我只是一个虾纸丫 提交于 2020-03-03 11:30:16

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;
    }
}

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!