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;
    }
};
相关推荐
神的孩子都在歌唱23 分钟前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
艾莉丝努力练剑2 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
汤姆爱耗儿药8 小时前
专为磁盘存储设计的数据结构——B树
数据结构·b树
许小燚16 小时前
线性表——双向链表
数据结构·链表
qqxhb18 小时前
零基础数据结构与算法——第四章:基础算法-排序(上)
java·数据结构·算法·冒泡·插入·选择
晚云与城18 小时前
【数据结构】顺序表和链表
数据结构·链表
FirstFrost --sy19 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Yingye Zhu(HPXXZYY)20 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle21 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
秋说1 天前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法