zoukankan      html  css  js  c++  java
  • 判断一个链表是不是循环链表

    算法思想:在建立循环链表时设置两个指针,头指针和尾指针,head和tail,使tail->next=head,即让尾节点指向头节点,建立的时候采用尾插入法,每次让新节点先指向尾节点的下一个节点,

    然后让头节点的下一个节点指向新节点,然后让新节点赋值给头节点和尾节点。

                  判断是否是循环链表时,也设置两个指针,慢指针和快指针,让快指针比慢指针每次移动快两次。如果快指针追赶上慢指针,则为循环链表,否则不是循环链表,如果快指针或者慢指针指向NULL,则不是循环链表。

    include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    typedef struct list
    {
        int data;
        struct list *next;
    }loopNode,*lpNode;
    
    void createList(lpNode &list,int arr[],int n)     //创建循环链表
    
    {
        lpNode node;
        lpNode head=NULL,tail=NULL;
        head=tail=list;
        tail->next=head;
        for(int i=0;i<n;i++)
         {
               node=(struct list*)malloc(sizeof(struct list));
               node->data=arr[i];
               node->next=tail->next;
               head->next=node;
               head=node;
               tail=node;
               
         }
        cout<<"create success"<<endl;
    }
    
    int judgeIsLoop(lpNode list)      //判断是否是循环链表
      
    {
         if(list==NULL)
            return 0;
         lpNode slow,fast;
         slow=list;
         fast=list->next->next;
         while(slow)
       {
         if(fast==NULL||fast->next==NULL)
             return 0;
         else if(fast==slow||fast->next==slow)
             return 1;
          else
              {
                slow=slow->next;
                fast=fast->next->next;
              }
       }
        return 0;
    }
    void display(lpNode list)     //输出循环链表
    {
         lpNode head,tail;
         head=tail=list;
         while(head->next!=tail)
           {
                cout<<head->data<<"--";
                head=head->next;
                
           }
            
           cout<<head->data;
          cout<<endl;
    }
    
    int main()
    {
        lpNode list=NULL;
        int arr[10]={1,2,3,4,5,6,7,8,9,0};
        int flag=0;
        list=(struct list*)malloc(sizeof(struct list));
        list->data=11;
        list->next=NULL;
        createList(list,arr,10);
        flag= judgeIsLoop(list);
        if(flag==1)                                   //如果是循环链表,就输出循环链表
        {
             cout<<"the list is loop list."<<endl;
             cout<<"output the list:"<<endl;
             display(list);
        }
        else
        {
             cout<<"the list is not loop list."<<endl;
        }
        cout<<endl;
        return 0;
        
    }
    

     运行截图:

  • 相关阅读:
    mockm remote 不能正常使用的解决方案
    uviewui 的 bug 当 url 的 query 参数中有 http://127.0.0.1/ 并且省略请求前缀的时候, 就会导致请求无法发送出去
    检查 nodmeon 是否可以修改文件后重启应用
    mocha 如何延迟指定时间后再运行所有用例
    使用 babel 编译 js 为 es5 支持 ie
    git 摘取提交
    Makefile学习笔记
    使用 Service Worker 缓解网站 DDOS 攻击
    如何热更新长缓存的 HTTP 资源
    网站图片无缝兼容 WebP/AVIF
  • 原文地址:https://www.cnblogs.com/xshang/p/3592571.html
Copyright © 2011-2022 走看看