每日一道 LeetCode (34):环形链表

每天 3 分钟,走上算法的逆袭之路。

前文合集

每日一道 LeetCode 前文合集

代码仓库

GitHub: https://github.com/meteor1993/LeetCode

Gitee: https://gitee.com/inwsy/LeetCode

题目:环形链表

题目来源:https://leetcode-cn.com/problems/linked-list-cycle/submissions/

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

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

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

解题方案

这道题其实蛮简单的,就是要看整个链表上有没有成环。

我开辟一个空间,比如一个哈希表或者其他什么的,把链表上的每一个元素一个一个往里面放,然后看看是否存在,如果存在就说明成环了,如果不存在,说明没有成环。

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

这种方案开辟一个新的空间,那么能不能不开辟新的空间呢?

public boolean hasCycle_1(ListNode head) {
    
    
    while (head != null) {
    
    
        if (head == head.next) {
    
    
            return true;
        }
        if (head.next != null) {
    
    
            head.next = head.next.next;
        }
        head = head.next;
    }
    return false;
}

这个方案是如果下一个元素不为空,则把 head.next 指向 head.next.next ,相当于是在整个链表上去掉了 head.next ,直到最后,如果成环的话,那么 head == head.next

您的扫码关注,是对小编坚持原创的最大鼓励:)

猜你喜欢

转载自blog.csdn.net/meteor_93/article/details/108355167