• 链表有环检测,环长度,环开始的地方


    #include<iostream>
    using namespace std;
    
    class node{
    public:
        node():value(0),next(NULL){}
        ~node(){}
        int value;
        node* next;
    };///be careful this ;
    
    node* createlist(int a[],int n)
    {
     node* startnode = new node[n];
     node* ret = startnode;
     for(int i = 0;i<n;i++)
     {
         startnode[i].value = a[i];
         if(i<n-1) 
             startnode[i].next = startnode + i + 1;
     }
     startnode[n-1].next = startnode + 5;
     for(int i = 0;i< 10;i++)
     {
         cout<<" "<<startnode->value;
         startnode = startnode->next;
     }
     cout<<endl;
     return ret;
    }
    
    bool iscircle(node* head)
    {
        if(NULL == head ||  NULL == head->next)
            return false;
        node* pslow = head;
        node* pfast = head->next;
        while(pfast && pfast->next)
        {
         if(pfast == pslow) return true;
         pslow = pslow->next;
         pfast = pfast->next->next;
        }
        return false;
    }
    
    
    int Length(node* head)
    {
        if(NULL == head ||  NULL == head->next)
            return 0;
    
        node* pslow = head;
        node* pfast = head->next;
        while(pfast && pfast->next)
        {
         if(pfast == pslow) 
         {
          int N = 1;
          pslow = pslow->next;
          while(pfast != pslow)
          {N++;pslow = pslow->next; }
          return N;
         }
         pslow = pslow->next;
         pfast = pfast->next->next;
        }
        return 0;
    }
    
    bool nodestartcircle(node* head)///十分注意起始点的选择
    {
        if(head == NULL || head->next == NULL) return false;
        node* pfast = head->next;
        node* pslow = head;
        while(pfast && pfast->next)
        {
         if(pfast == pslow) 
         { 
             cout<<pfast->value<<endl;
             pfast = pfast->next;
             pslow = head;
             while(pfast != pslow){pfast = pfast->next;pslow = pslow->next;}
             cout<<pslow->value<<endl;
             return true;
         }
         pslow = pslow->next;
         pfast = pfast->next->next;
        }
        return false;
    }
    
    
    int main()
    {
        int a[] = {1,2,3,4,5,6,7,8,9};
        node * t = createlist(a,9);
        //cout<<iscircle(t);
        //Length(t);
        cout<<nodestartcircle(t);
    }
    berkeleysong
  • 相关阅读:
    vmware克隆linux出错:Device eth0 does not seem to be present
    IDEA中项目路径问题
    Intellij idea 报错:Error : java 不支持发行版本5
    equals和==的区别
    指定Python版本下pip安装“pip install”
    大数据5V特点(5Vs of Big Data)
    大二下每周总结
    大二 下学期——期末个人总结(课程评价及加分项)
    大二下学期第二次个人作业第二阶段
    大二下学期第二次个人作业第二阶段
  • 原文地址:https://www.cnblogs.com/berkeleysong/p/3740616.html
Copyright © 2020-2023  润新知