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;
            }
        }
    };
  • 相关阅读:
    LeetCode 654. 最大二叉树
    LeetCode 617. 合并二叉树
    LeetCode 234. 回文链表
    LeetCode 328. 奇偶链表
    LeetCode 24. 两两交换链表中的节点
    LeetCode 21. 合并两个有序链表
    LeetCode 876. 链表的中间结点
    顺序表的定义及其相关基本操作
    LeetCode 206. 反转链表
    LeetCode 111. 二叉树的最小深度
  • 原文地址:https://www.cnblogs.com/wxquare/p/6848562.html
Copyright © 2011-2022 走看看