• 算法训练 第三周


    二、环形链表

    在这里插入图片描述
    本题给了我们一个链表的头节点,需要我们判断这个链表之中是否存在环状结构,如果存在返回true,如果不存在则返回false。

    1.hash表

    我们可以从头遍历整个链表,并将遍历到的节点放入一个hashset中,当我们遍历到的节点与hashset中的节点出现重复时就说明链表存在环,如果我们遍历完了整个链表那就说明不存在环,具体代码如下:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null || head.next == null) {
                return false;
            }
            ListNode node = head;
            HashSet<ListNode> set = new HashSet<>();
            while(node != null) {
                if(set.contains(node)) {
                    return true;
                }
                set.add(node);
                node = node.next;
            }
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    复杂度分析
    • 时间复杂度:O(n)。
    • 空间复杂度:O(n)。

    2.双指针

    我们可以定义两个指针来遍历这个链表,慢指针每次走一个节点,快指针每次走两个节点,如果在遍历的过程中快指针与慢指针相遇则说明有环,否则就没有环,具体代码如下:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null || head.next == null) {
                return false;
            }
            ListNode f = head;
            ListNode s = head;
            while(f != null && f.next != null) {
                f = f.next.next;
                s = s.next;
                if(f == s) {
                    return true;
                }
            }
            return false;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    复杂度分析
    • 时间复杂度:O(n)。
    • 空间复杂度:O(1)。
  • 相关阅读:
    【HTML专栏2】VSCode的使用(新建HTML文件)
    springcloud22:sentinal的使用
    用 VS Code 搞 Qt6:信号、槽,以及QObject
    C++数据结构之顺序栈
    Spring cloud alibaba
    MySQL数据库备份全攻略:从基础到高级,一文掌握所有备份技巧
    gcc和g++区别
    ant design ant design Pro 中的table横向与纵向合并问题
    springboot(ssm 企业员工薪酬关系系统 Java(code&LW)
    PHP基于thinkphp的网上图书管理系统#毕业设计
  • 原文地址:https://blog.csdn.net/Gatcher/article/details/133048824