8.16 哈希表中等 142 Linked List Cycle II review 141 Linked List Cycle

142 Linked List Cycle II


cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        //给一个链表的头头,返回循环的开始结点 如果没有循环返回null
        //判断有环的情况
        //环的位置判断,
        //哈希表使用--->快速查找
        unordered_set<ListNode*> nodeSet;
        ListNode *p = head;//尾指针
        while(p){
            if(nodeSet.find(p) == nodeSet.end()){
                //没找到
                nodeSet.insert(p);
            }else{
                return p;
            }
            p = p->next;
        }
        return nullptr;
    }
};

空间复杂度为O(1)

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        //判断有环的情况-->同一个结点反复出现-->结点之间做比较-->双指针
        //环的位置判断-->pre比p先一步进入环中所以pre应该一直==p->next,此时pre直接一个绕后但他还是p->next
        //**怎么判断两个指针能够相撞呢**,一个跑的快一个跑得慢直至慢的被快的套圈,但不能保证套圈位置是在环的开头--->快慢指针
        //**怎么保证返回的结点是环的第一个结点**?-->计算
        if (!head || !head->next) return nullptr;
        ListNode *fast = head;
        ListNode *slow  = head;
        while(fast&&fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(fast == slow){
                // 将其中一个指针移到链表头部
                ListNode *p = head;
                
                // 两个指针同时向前移动
                while (p != slow) {
                    p = p->next;
                    slow = slow->next;
                }
                
                // 返回环的起始节点
                return p;
            }
        }
        return nullptr;
    }
};

review 8.8 141 Linked List Cycle


cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        //快慢指针
        if(!head || !head->next) return false;
        ListNode *fast = head;
        ListNode *slow = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow){
                return true;
            }
        }
        return false;
    }
};
相关推荐
ATAOL32 分钟前
数据结构一
数据结构·算法
罗超驿2 小时前
Java数据结构_链表
java·数据结构·链表
AMoon丶4 小时前
Golang--多种数据结构详解
linux·c语言·开发语言·数据结构·c++·后端·golang
宵时待雨5 小时前
C++笔记归纳10:继承
开发语言·数据结构·c++·笔记·算法
田梓燊5 小时前
最长的连续序列到底怎么写
算法·哈希算法·散列表
一叶落4385 小时前
LeetCode 21. 合并两个有序链表(C语言详解 | 链表经典题)
c语言·数据结构·c++·算法·leetcode·链表
阿里嘎多哈基米5 小时前
速通Hot100-Day04——哈希
数据结构·算法·leetcode·哈希算法·散列表
WolfGang0073215 小时前
代码随想录算法训练营 Day10 | 栈与队列 part02
数据结构
Darkwanderor6 小时前
数据结构——树状数组和在线、离线操作
数据结构·c++·树状数组·离线操作
仟濹6 小时前
【算法打卡day22(2026-03-14 周六)今日算法or技巧:双指针 & 链表】9个题
数据结构·算法·链表·双指针