zoukankan      html  css  js  c++  java
  • 环形链表判断

    题目:

    141-环形链表

    https://leetcode-cn.com/problems/linked-list-cycle/

    解答:

    思路:将访问过的放到一个容器中,然后判断当前访问的节点是否已经存在容器内

    代码:

    //141-1 放到容器中,判断当前的节点是否在已访问的容器内
    bool hasCycle(ListNode *head) 
    {
        vector<ListNode*> hasFound;
        while (head != nullptr)
        {
            if (hasFound.size() > 0 && find(hasFound.begin(), hasFound.end(), head) != hasFound.end())
                return true;
    
            hasFound.push_back(head);
            head = head->next;
        }
    
        return false;
    }

    提交后:5%,时间复杂度O(n),空间复杂度O(n),因为使用了额外的容器

    解答二:双指针法--快慢指针

    思路:

    两个指针同时指向head,一个每次移动一个节点,一个每次移动两个节点,如果两个节点在某一时刻相遇,则有环;如果某个指针指向了nullptr则无环

    原理:两个人绕跑道跑步,快的最终会套圈跑的慢的,也即是两者一段时间后必须相遇。

    代码:

    //快慢指针
    bool hasCycle2(ListNode *head)
    {
        if (head == nullptr)
            return true;
        ListNode* p1 = head;
        ListNode* p2 = head->next;    //注意:在这里不能将p2 赋值为head,不然 p1直接等于p2 了
        while (p1 != p2)//截止条件:p1 p2指向相同的节点
        {
            p1 = p1->next;
            if (p1 == nullptr)
                return false;
            if (p2->next == nullptr)
                return false;
            p2 = p2->next->next;
            if (p2 == nullptr)
                return false;
        }
    
        return true;
    }
  • 相关阅读:
    Adobe PS
    深入学习二叉树(04)平衡二叉树
    深入学习二叉树(03)二叉查找树
    C 知识点
    实战【docker 镜像制作与使用】
    从0到1了解 CI/CD
    单例模式的几种实现方式,使用场景以及优缺点
    设计模式之策略模式浅谈以及简单例子
    WPF几种渐变色
    Linq学习以及简单用法
  • 原文地址:https://www.cnblogs.com/zyk1113/p/14048802.html
Copyright © 2011-2022 走看看