码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 142. Linked List Cycle II

时间:2019-12-19 13:11:36      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:int   res   entry   integer   HERE   connect   val   tail   ctc   

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

标签:int   res   entry   integer   HERE   connect   val   tail   ctc   

原文地址:https://www.cnblogs.com/xuanlu/p/12066983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!