zoukankan      html  css  js  c++  java
  • 114 判断一个链表是否存在环并返回环起点

    方法一 活用set

       ListNode *detectCycle(ListNode *head) {
            set<ListNode *> save;
            while (head != nullptr)
                if (save.find(head) != save.end())
                    return *save.find(head);
                else {
                    save.emplace(head);
                    head = head->next;
                }
            return nullptr;
        }
    

    方法二 快慢指针

        ListNode *detectCycle(ListNode *head) {
            if(head==nullptr)
                return nullptr;
            ListNode *slow = head, *fast = head;
            while(true){
                if(fast->next==nullptr||fast->next->next==nullptr)
                    return nullptr;
                slow=slow->next;
                fast=fast->next->next;
                if(slow==fast){
                    while(head!=fast){
                        head=head->next;
                        fast=fast->next;
                    }
                    return head;
                }
            }
        }
    
  • 相关阅读:
    CSPS模拟 57
    CSPS模拟 56
    CSPS Oct目标
    CSPS模拟 55
    CSPS模拟 54
    CSPS模拟 53
    和manacher有关的乱写
    CSPS模拟 52
    CSPS模拟 51
    Git和代码规范
  • 原文地址:https://www.cnblogs.com/INnoVationv2/p/10152627.html
Copyright © 2011-2022 走看看