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;
    }
};
相关推荐
Yeats_Liao15 小时前
MindSpore开发之路(八):数据处理之Dataset(上)——构建高效的数据流水线
数据结构·人工智能·python·机器学习·华为
客梦16 小时前
数据结构-线性表
数据结构·笔记
鹿角片ljp16 小时前
力扣226.翻转二叉树-递归
数据结构·算法·leetcode
WBluuue16 小时前
数据结构和算法:Morris遍历
数据结构·c++·算法
客梦16 小时前
数据结构-红黑树
数据结构·笔记
Sheep Shaun17 小时前
STL:string和vector
开发语言·数据结构·c++·算法·leetcode
winfield82117 小时前
滑动时间窗口,找一段区间中的最大值
数据结构·算法
k***921618 小时前
list 迭代器:C++ 容器封装的 “行为统一” 艺术
java·开发语言·数据结构·c++·算法·list
x70x8019 小时前
C++中auto的使用
开发语言·数据结构·c++·算法·深度优先
sin_hielo19 小时前
leetcode 2054(排序 + 单调栈,通用做法是 DP)
数据结构·算法·leetcode