detectCycle

2020-07-14  本文已影响0人  瞬铭

https://leetcode.com/problems/linked-list-cycle-ii/
给定一个链表,判断是否有环,并且返回环开始的那个ListNode

    public ListNode detectCycle(ListNode head) {
      Set<ListNode> se = new HashSet<ListNode>();
        ListNode tmp = head;
        se.add(tmp);
        while (tmp != null && tmp.next != null) {
            tmp = tmp.next;
            if (se.contains(tmp)) {
                return tmp;
            }
            se.add(tmp);
        }
        return null;
    }

参考:https://www.cnblogs.com/grandyang/p/4137302.html

        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                break;
            }
        }
        if (fast == null || fast.next == null) {
            return null;
        }

        slow = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }

上一篇 下一篇

猜你喜欢

热点阅读