141.环形链表 & 142.环形链表II

141.环形链表 & 142.环形链表II

141.环形链表

思路:快慢指针 or 哈希表

快慢指针代码:

cpp 复制代码
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==nullptr||head->next==nullptr)
        return false;
        ListNode *fast=head->next; //不能设置成head,否则不进入while循环
        ListNode *slow=head;
        while(fast!=slow){
            //如果无环fast在slow前面,只需要判断fast
            if(fast->next!=nullptr&&fast->next->next!=nullptr){
                fast=fast->next->next;
                slow=slow->next;
            }else{  //无环
                return false;
            }
        }
        return true;
    }
};

哈希表代码:

cpp 复制代码
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> hash;
        ListNode* cur=head;
        while(cur!=nullptr){
            //哈希表中出现过
            if(hash.count(cur)){
                return cur;
            }
            hash.insert(cur);
            cur=cur->next;
        }
        return nullptr;
    }
};

142.环形链表II

思路:快慢指针+数学推导 or 哈希表

哈希表同前,数学推导见下图,

代码:

cpp 复制代码
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr) {
            slow = slow->next;
            if (fast->next == nullptr) {
                return nullptr;
            }
            fast = fast->next->next;
            if (fast == slow) {
                ListNode *ptr = head;
                while (ptr != slow) {
                    ptr = ptr->next;
                    slow = slow->next;
                }
                return ptr;
            }
        }
        return nullptr;
    }
};
相关推荐
lunar_coder1 小时前
哈希扩展 -- 位图思想
c++·算法·哈希算法
秋天的怀念_David2 小时前
听故事学语言 · 数据结构篇 · 序章一 算法之问
数据结构·程序人生·算法
-dzk-2 小时前
【链表】LC 25.K 个一组翻转链表
数据结构·链表
careathers3 小时前
【数据结构】基于比较的排序算法 - 插入排序
java·数据结构·排序算法
MicrosoftCloud3 小时前
数据结构 07(上)|查找:顺序、折半、分块,ASL 到底怎么
数据结构·查找·顺序查找·折半查找·分块查找·平均查找长度·asl
Mortalbreeze3 小时前
0 - 1 BFS 算法详解:从基本原理到经典题目建模
数据结构·c++·算法·图论·宽度优先
shehuiyuelaiyuehao18 小时前
算法56,重排链表
数据结构·算法·链表
qq_4523962318 小时前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》
算法·哈希算法·gin
suhan19 小时前
【数据结构】七、查找:1.查找的概念、线性结构查找(顺序、折半(二分)、插值、稠密、分块、倒排)
数据结构·算法·排序算法
极客 - L U19 小时前
卡尔曼滤波从零到精通
c语言·数据结构·单片机·嵌入式硬件·mcu