[LC] 142. Linked List Cycle II

Posted xuanlu

tags:

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

 

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                // get the entry point when cur and slow meet
                ListNode cur = head;
                while(cur != slow) {
                    cur = cur.next;
                    slow = slow.next;
                }
                return slow;
            }
        }
        return null;
    }
}

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

142. Linked List Cycle II

142. Linked List Cycle II

142. Linked List Cycle II

LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

142. Linked List Cycle II

142. Linked List Cycle II