• 面试题7:判断链表是否有环,返回环的入口点


    1.Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    /**
     * 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==nullptr || head->next == nullptr) return false;
            ListNode* slow = head;
            ListNode* fast = head;
            while(fast && fast->next){
                slow = slow->next;
                fast = fast->next->next;
                if(slow == fast){
                    return true;
                }
            }
            return false;
        }
    };

    2.Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

    Follow up:
    Can you solve it without using extra space?

    /**
     * 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){
            if(head == nullptr || head->next == nullptr) return nullptr;
            ListNode* slow = head;
            ListNode* fast = head;
    
            ListNode* crossNode = nullptr;
            while(fast && fast->next){
                slow = slow->next;
                fast = fast->next->next;
                if(slow == fast){
                    crossNode = slow;
                    break;
                }
            }
            if(crossNode == nullptr){
                return nullptr;
            }else{
                slow = head;
                while(slow != crossNode){
                    slow = slow->next;
                    crossNode = crossNode->next;
                }
                return crossNode;
            }
        }
    };
  • 相关阅读:
    前端面试题精选
    闭包、作用域、THIS、OOP
    Ubuntu,debian一键安装Mariadb
    两条命令实现nodejs快速安装
    HTML 5的革新——语义化标签section和article的区别
    uni-app之uni.showToast()image路径问题
    vue-cli4配置文件别名
    蓝湖使用方法
    Node组件——Express简介
    程序员最深情的告白——《致对象》
  • 原文地址:https://www.cnblogs.com/wxquare/p/6848562.html
Copyright © 2020-2023  润新知