LeetCode 142 链表 Linked List Cycle II

Posted Muche

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

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




以上是关于LeetCode 142 链表 Linked List Cycle II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 142. Linked List Cycle II

Leetcode 142题 环形链表 II(Linked List Cycle II) Java语言求解

25.leetcode142_linked_list_cycle_II

142 Linked List Cycle II 环形链表 II

LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

leetcode 141 142. Linked List Cycle