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;
    }
};
相关推荐
放荡不羁的野指针2 分钟前
leetcode150题-滑动窗口
数据结构·算法·leetcode
BHXDML20 分钟前
数据结构:(一)从内存底层逻辑理解线性表
数据结构
小龙报24 分钟前
【C语言进阶数据结构与算法】单链表综合练习:1.删除链表中等于给定值 val 的所有节点 2.反转链表 3.链表中间节点
c语言·开发语言·数据结构·c++·算法·链表·visual studio
Anastasiozzzz1 小时前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
xuedingbue2 小时前
数据结构与顺序表:高效数据管理秘籍
数据结构·算法·链表
啊阿狸不会拉杆3 小时前
《数字信号处理 》第 7 章-无限长单位冲激响应 (IIR) 数字滤波器设计方法
数据结构·算法·信号处理·数字信号处理·dsp
挽天java4 小时前
数据结构习题--寻找旋转排序数组中的最小值
数据结构·算法·排序算法
sin_hielo5 小时前
leetcode 1984
数据结构·算法·leetcode
定偶5 小时前
网络编程总结
开发语言·网络·数据结构·网络编程