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;
    }
};
相关推荐
code bean1 天前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
storyseek1 天前
前缀和实现Kogge-Stone算法
数据结构·算法
元Y亨H1 天前
深度解构:数据结构与算法的理论基石与工程演进
数据结构·算法
元Y亨H1 天前
数据结构与算法的通俗指南
数据结构·算法
2301_764441331 天前
用动力学系统(微分方程)为 Kernberg 的客体关系单元提供数学化的操作定义,把“自体—客体“这对心理结构建模成一个二维耦合系统
数据结构·python·算法·数学建模
ChaoZiLL1 天前
我读数据结构5-树
数据结构
冻柠檬飞冰走茶1 天前
PTA基础编程题目集 7-7 12-24小时制(C语言实现)
c语言·开发语言·数据结构·算法
雨落在了我的手上1 天前
Java数据结构(八):双链表的实现
数据结构
paeamecium1 天前
【PAT甲级真题】- Kuchiguse (20)
数据结构·c++·python·算法·pat考试·pat
青山木1 天前
Hot 100 --- 全排列
java·数据结构·算法·leetcode·深度优先