zoukankan      html  css  js  c++  java
  • 单链表有环判断问题解决办法

    #include <iostream>
    #include <unordered_set>
    #include <algorithm>
    using namespace std;
    typedef int ElemType;
    typedef struct LinkNode
    {
        ElemType data;
        LinkNode *next;
    }LinkList;
    LinkNode* Init_LinkNode()
    {
        LinkNode *head = (LinkNode*)malloc(sizeof(LinkNode));
        head->next = nullptr;
        head->data = 0; //存储链表长度
        return head;
    }
    void Create_LinkNode(LinkNode *head)
    {
        //头插法
        LinkNode *p = head,*s,*q=head;
        cout<<"please input the sequence:";
        ElemType x;
        cin>>x;
        while (x != 999)
        {
            s = (LinkNode*)malloc(sizeof(LinkNode));
            s->data = x;
            s->next = head->next;
            p->next = s;
            p->data++;
            //q指针是为了找到末尾指针,建立环
            q->next=s;
            q=s;
            cin>>x;
        }
        //建立环
        q->next = head->next;
    }
    //判断环形链表方法1.哈希表方法
    bool has_Cycle(LinkNode *head)
    {
        unordered_set<LinkNode*> seen;
        LinkNode *p = head->next;
        while(p)
        {
            if (seen.count(head))
                return true;  //哈希表中有表示有环
            seen.insert(head);  //插入哈希表
            p = p->next;
        }
        return false;
    }
    bool has_cycle(LinkNode *head)
    {
        //双指针判断单链表中是否有环,慢指针每次走1步,快指针走每次走两步,有环走表长次一定相遇
        LinkNode *fast = head->next,*slow = head->next;
        while (slow && fast && fast->next)
        {
            if (slow == fast)
            {
                cout<<"单链表长度为:"<<head->data<<endl;
                return true;
            }
            slow = slow->next;
            fast = fast->next->next;
        }
        return false;
    }
    void show(LinkNode *head)
    {
        LinkNode *p = head->next;
        while (p)
        {
            cout<<p->data<<endl;
            p = p->next;
        }
    }
    int main()
    {
        LinkNode *head = Init_LinkNode();
        Create_LinkNode(head);
    //    show(head);
        if (has_Cycle(head))
            cout<<"有环
    ";
        else
            cout<<"无环"<<endl;
        if (has_cycle(head))
            cout<<"有环
    ";
        else
            cout<<"无还"<<endl;
        return 0;
    }
  • 相关阅读:
    python学习--函数
    python学习--变量
    python学习--运算符
    python学习--数据类型
    python学习--循环语句
    年轻不言失败
    《zero to one》读后感
    进程与线程
    JS----模块化
    js 一个等号"=" 二个等号"==" 三个等号"===" object.is()的区别
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/15154871.html
Copyright © 2011-2022 走看看