Linked List Cycle

来源:互联网 发布:利用php漏洞进行提权 编辑:程序博客网 时间:2024/06/03 17:50

Description:

Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
分析
最容易想到的方法是,用一个哈希表 unordered_map< int, bool > visited,记录每个元素是否被访问过,一旦出现某个元素被重复访问,说明存在环。空间复杂度 O(n),时间复杂度 O(N )。
最好的方法是时间复杂度 O(n),空间复杂度 O(1) 的。设置两个指针,一个快一个慢,快的 指 针 每 次 走 两 步, 慢 的 指 针 每 次 走 一 步, 如 果 快 指 针 和 慢 指 针 相 遇, 则 说 明 有 环。

#include <iostream>#include <limits.h>using namespace std;struct LNode{    int val;    LNode *next;    LNode(int x):val(x),next(nullptr) {}};class Solution{    public:        bool hasCircle(LNode *L)        {            if (L == nullptr || L->next == nullptr)                return false;            LNode *slow = L, *fast = L;            while (fast && fast->next)            {                slow = slow->next;                fast = fast->next->next;                if (slow == fast)                    return true;            }            return false;        }};int main(void){    LNode *List = new LNode(INT_MIN);    LNode *ptr = List;    int n;    cout<<"Input the number: "<<endl;    cin>>n;    for (int i =0; i < n; i++)    {        ptr->next = new LNode(i);        ptr = ptr->next;    }    ptr->next = List->next; //circle    Solution solution;    bool result = solution.hasCircle(List->next);    if (result)        cout<<"The list has a circle."<<endl;    else        cout<<"There is no circle in the list."<<endl;    LNode *pointer = List;    for (int i = 0 ;i <= n; ++i)    {        pointer = List->next;        delete List;        List = pointer;    }    return 0;}

这里写图片描述

0 0