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;
    }
};
相关推荐
小欣加油8 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL9 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
zzzsde10 小时前
【数据结构】队列
数据结构·算法
青 .10 小时前
数据结构---二叉搜索树的实现
c语言·网络·数据结构·算法·链表
MChine慕青11 小时前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
数据爬坡ing12 小时前
从挑西瓜到树回归:用生活智慧理解机器学习算法
数据结构·深度学习·算法·决策树·机器学习
胡耀超13 小时前
3.Python高级数据结构与文本处理
服务器·数据结构·人工智能·windows·python·大模型
云:鸢13 小时前
C语言链表设计及应用
c语言·开发语言·数据结构·链表
在下雨59915 小时前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
今后12315 小时前
【数据结构】栈详解
数据结构·