leetcode刷题(28)——141.环形链表

一、题目

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

leetcode刷题(28)——141.环形链表_第1张图片
leetcode刷题(28)——141.环形链表_第2张图片
进阶:

你能用 O(1)(即,常量)内存解决此问题吗?

二、思路及代码

思路一:双指针

创建两个指针,慢指针一次走一步,快指针一次走两步。两个指针同时从头节点出发,如果链表没有环,则快指针先到达 null;如果有环,则两个指针一定会在环内相遇。

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

思路二:哈希表

利用哈希表不存储重复元素的特点,检查一个节点是否被访问过来判断链表是否有环。

遍历链表并将所有节点存储在哈希表中,如果遍历到某个节点发现它已经存在于哈希表中,说明链表有环;否则,就不是环形链表。

public 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;
    }
}

你可能感兴趣的:(leetcode刷题,链表,指针,leetcode,数据结构,java)