美文网首页数据结构
Linked List Cycle II(带环链表 II)

Linked List Cycle II(带环链表 II)

作者: Frank_Kivi | 来源:发表于2017-09-21 23:40 被阅读1次

问题

Given a linked list, return the node where the cycle begins.

If there is no cycle, return null.

Have you met this question in a real interview? Yes
Example
Given -21->10->4->5, tail connects to node index 1,return 10

分析

请参阅 Intersection of Two Linked Lists(两个链表的交叉)

代码

/**
 * Definition for ListNode.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int val) {
 * this.val = val;
 * this.next = null;
 * }
 * }
 */


public class Solution {
    /*
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. if there is no cycle, return null
     */
    public ListNode detectCycle(ListNode head) {
        // write your code here
        if (head == null) {
            return null;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (true) {
            if (fast == null || fast.next == null) {
                return null;
            }
            if (fast == slow) {
                break;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        slow = head;
        fast = fast.next;
        while (true) {
            if (slow == fast) {
                return slow;
            }
            slow = slow.next;
            fast = fast.next;
        }
    }
}

相关文章

网友评论

    本文标题:Linked List Cycle II(带环链表 II)

    本文链接:https://www.haomeiwen.com/subject/zwhxextx.html