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;
    }
};
相关推荐
Marzlam7 小时前
一文读懂数据结构
数据结构
南玖yy7 小时前
探索 C 语言数据结构:从基础到实践
c语言·开发语言·数据结构
风掣长空7 小时前
八大排序——c++版
数据结构·算法·排序算法
しかし1181149 小时前
C语言队列的实现
c语言·开发语言·数据结构·数据库·经验分享·链表
owde10 小时前
数据结构-顺序表
数据结构·线性表·定长顺序表·不定长顺序表
小开不是小可爱10 小时前
leetcode_454. 四数相加 II_java
java·数据结构·算法·leetcode
aaaweiaaaaaa11 小时前
蓝桥杯c ++笔记(含算法 贪心+动态规划+dp+进制转化+便利等)
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
h^hh12 小时前
pipe匿名管道实操(Linux)
数据结构·c++·算法
学习编程的gas12 小时前
数据结构——二叉树
数据结构·算法
Chiyamin14 小时前
图算法基础
数据结构·c++·算法