【LeetCode】141. 环形链表(Linked List Cycle)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27124771/article/details/84874170

英文练习 | 中文练习

题目描述: 给定一个链表,判断链表中是否有环。

解题思路: 一种方法可以使用 Hash Table ,判断该结点之前是否遇到过;更优的方法是使用双指针,一个指针每次移动一个结点,一个指针每次移动两个结点,如果存在环,那么这两个指针一定会相遇。

public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) {
        return false;
    }
    ListNode slow = head;
    ListNode fast = head.next;
    while (slow != fast) {
        if (fast == null || fast.next == null) {
            return false;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
}

猜你喜欢

转载自blog.csdn.net/qq_27124771/article/details/84874170
今日推荐