当前位置: 首页 > article >正文

141.环形链表 142.环形链表II

141.环形链表 & 142.环形链表II

141.环形链表

思路:快慢指针 or 哈希表

快慢指针代码:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==nullptr||head->next==nullptr)
        return false;
        ListNode *fast=head->next; //不能设置成head,否则不进入while循环
        ListNode *slow=head;
        while(fast!=slow){
            //如果无环fast在slow前面,只需要判断fast
            if(fast->next!=nullptr&&fast->next->next!=nullptr){
                fast=fast->next->next;
                slow=slow->next;
            }else{  //无环
                return false;
            }
        }
        return true;
    }
};

哈希表代码:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_set<ListNode*> hash;
        ListNode* cur=head;
        while(cur!=nullptr){
            //哈希表中出现过
            if(hash.count(cur)){
                return cur;
            }
            hash.insert(cur);
            cur=cur->next;
        }
        return nullptr;
    }
};

142.环形链表II

思路:快慢指针+数学推导 or 哈希表

哈希表同前,数学推导见下图,

在这里插入图片描述

代码:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr) {
            slow = slow->next;
            if (fast->next == nullptr) {
                return nullptr;
            }
            fast = fast->next->next;
            if (fast == slow) {
                ListNode *ptr = head;
                while (ptr != slow) {
                    ptr = ptr->next;
                    slow = slow->next;
                }
                return ptr;
            }
        }
        return nullptr;
    }
};


http://www.kler.cn/a/471664.html

相关文章:

  • Azure主机windows2008就地升级十步
  • torch.max和torch.softmax python max
  • hpm使用笔记————使用usb作为从机接收来自上位机的数据然后通过spi主机发送给spi从机
  • 使用 PyTorch 自定义数据集并划分训练、验证与测试集
  • Mysql--基础篇--数据类型(整数,浮点数,日期,枚举,二进制,空间类型等)
  • Jupyter Markdown样式说明
  • HTML静态网页成品作业(HTML+CSS)——婚礼婚纱网页设计制作(6个页面)
  • OSPF使能配置
  • 攻防靶场(32):两个爆破技巧 Funbox 7 EasyEnum
  • 5. 多线程(3) --- synchronized
  • 力扣经典题目之2283. 判断一个数的数字计数是否等于数位的值
  • [网络安全]DVWA之File Upload—AntSword(蚁剑)攻击姿势及解题详析合集
  • windows蓝屏以及windows补丁回滚
  • Solaris操作系统
  • JavaScript系列(12)-- 高阶函数应用
  • Spring5框架之SpringMVC
  • 记录一下Coding一直不能clone
  • 7_TypeScript Number --[深入浅出 TypeScript 测试]
  • Ae:合成设置 - 3D 渲染器
  • 除了RAII和智能指针,还有哪些资源管理机制?