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

LeetCode 142 链表 Linked List Cycle II

时间:2020-03-03 10:50:36      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:slow   else   contain   over   Plan   ace   return   相等   res   

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

标签:slow   else   contain   over   Plan   ace   return   相等   res   

原文地址:https://www.cnblogs.com/muche-moqi/p/12400849.html

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