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;
    }
};
相关推荐
奔跑吧 android19 小时前
【linux kernel 常用数据结构和设计模式】【数据结构 2】【通过一个案例属性list、hlist、rbtree、xarray数据结构使用】
linux·数据结构·list·kernel·rbtree·hlist·xarray
默默无名的大学生21 小时前
数据结构—顺序表
数据结构·windows
Jared_devin21 小时前
二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值
数据结构·c++·算法·职场和发展·蓝桥杯
siy23331 天前
[c语言日记] 数组的一种死法和两种用法
c语言·开发语言·笔记·学习·链表
AI 嗯啦1 天前
数据结构深度解析:二叉树的基本原理
数据结构·算法
hai_qin1 天前
十三,数据结构-树
数据结构·c++
和光同尘@1 天前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
我爱996!1 天前
LinkedList与链表
数据结构·链表
yb0os11 天前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc
hope_wisdom1 天前
C/C++数据结构之栈基础
c语言·数据结构·c++··stack