zoukankan      html  css  js  c++  java
  • 面试题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;
            }
        }
    };
  • 相关阅读:
    bzoj 1858 线段树
    bzoj 1877 最小费用流
    bzoj 1833 数位dp
    Codeforces Round #285 (Div. 1) B
    HDU2028 Lowest Common Multiple Plus
    HDU5706 GirlCat
    HDU2022 海选女主角
    687E: TOF
    687D: Dividing Kingdom II
    687D: Dividing Kingdom II
  • 原文地址:https://www.cnblogs.com/wxquare/p/6848562.html
Copyright © 2011-2022 走看看