141 . 环形链表

链接

https://leetcode.cn/problems/linked-list-cycle/description/?envType=study-plan-v2&envId=top-interview-150

题面

思路 :

法1 :

用哈希表来存之前的遍历过的结点 ;

一遍遍历,在遍历的过程中,先判断是否当前结点在哈希表中出现过,如果出现过,直接返回true;

否则继续遍历,如果到遍历结束,证明没有环,直接返回false;

复制代码
class Solution {
public:
    bool hasCycle(ListNode *head) {
        set<ListNode*> st ;
        while(head){
            if(st.count(head)) return true;
            st.insert(head);
            head = head -> next ;
        }
        return false;
    }
};

法2

直接判断循环次数,因为也就最多也就1e4个结点,那么如果有环的话,那么一定会出现遍历次数大于10000的,在遍历的过程中,判断n是否大于10000,是的话,直接返回true;否则返回false ;

复制代码
class Solution {
public:
    bool hasCycle(ListNode *head) {
        int n = 0 ;
        while(head != nullptr){
            n++ ;
            head = head->next ;
            if(n>10010){
                return true;
            }
        } 
        return false;
    }
};

法3

快慢双指针 -- > 算是本题的最优解了 ;

定义一个快慢双指针,快的每次跑两步,慢的每次跑一步;

如果存在环的话,那么快慢双指针一定都会进入环中,用相对速度思考,慢的不懂,快的每次前进一步,那么在环中,两个一定会相遇 ;

复制代码
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr || head->next == nullptr) return false;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(slow != fast){
            if(fast == nullptr || fast->next == nullptr){
                return false;
            }
            slow = slow->next;
            fast = fast->next->next;
        } 
        return true;
    }
};
相关推荐
Python_Study20251 分钟前
工程材料企业如何通过智慧获客软件破解市场困局:方法论、架构与实践
大数据·网络·数据结构·人工智能·架构
学嵌入式的小杨同学42 分钟前
【嵌入式 C 语言高频考点】周测 + 期中真题解析:从基础语法到编程实战
c语言·数据结构·数据库·vscode·算法·面试
福楠1 小时前
C++ | 红黑树
c语言·开发语言·数据结构·c++·算法
dazzle2 小时前
Python数据结构(五):队列详解
数据结构·python
爱编码的傅同学2 小时前
【今日算法】LeetCode 25.k个一组翻转链表 和 43.字符串相乘
算法·leetcode·链表
stolentime2 小时前
P14978 [USACO26JAN1] Mooclear Reactor S题解
数据结构·c++·算法·扫描线·usaco
dazzle2 小时前
Python数据结构(四):栈详解
开发语言·数据结构·python
充值修改昵称3 小时前
数据结构基础:B+树如何优化数据库性能
数据结构·b树·python·算法
Cinema KI3 小时前
一键定位,哈希桶的极速魔法
数据结构·c++·算法·哈希算法
曾几何时`3 小时前
二分查找(九)2300. 咒语和药水的成功对数
数据结构·算法