zoukankan      html  css  js  c++  java
  • 链表有环检测,环长度,环开始的地方

    #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
  • 相关阅读:
    重链剖分的总结与模板
    PBDS学习笔记(一)
    LCT 第一题 洛谷模板
    2018年暑假第四次周赛-图论部分题解
    后缀数组求不同子串的个数
    Codeforces Round #106 (Div. 2) Coloring Brackets(区间DP)
    Codeforces Round #510 (Div. 2) D. Petya and Array (权值线段树)
    HDU 3974 Assign the task (dfs序+线段树)
    Manthan, Codefest 18 (rated, Div. 1 + Div. 2) D.Valid BFS? (模拟)
    POJ
  • 原文地址:https://www.cnblogs.com/berkeleysong/p/3740616.html
Copyright © 2011-2022 走看看