LeetCode【141.环形链表】

版权声明: https://blog.csdn.net/qq_38386316/article/details/83017419

题目描述

给定一个链表,判断链表中是否有环。

思路 * 1
还是使用快慢指针的思路进行遍历,如果有环的话,快慢指针总会相遇于一个结点;否则快指针也会走到null,跳出循环。可以想象两个人在操场跑步的场景,一个跑的慢,一个跑的快。
代码 * 1

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

思路 * 2
使用哈希表进行存储,类型为ListNode, 存储过程中,如果哈希表中出现已有的结点,则说明有环。

代码 * 2

class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while(head != null) {
            if(set.contains(head) ) {
                return true;
            }else {
                set.add(head);
            }
            head = head.next;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38386316/article/details/83017419