zoukankan      html  css  js  c++  java
  • 判断一个单向链表中是否存在环

    方法一:使用map来记录链表中的结点是否被访问,若存在被访问两次的结点则说明存在环。

    #include "iostream"
    #include "map"
    using namespace std;
    map<node*,int>m;
    bool IsLoop(node *head)
    {
          if(!head)
               return false;
          node *p=head;
          while(p)
         {
               if(m[p]==0) // 默认值都是0
                    m[p]=1;
               else if(m[p]==1)
                    return true;
               p=p->next;
         }
    }
    

     
    方法二:设置 两个指针pSlow,pFast,慢的一次跳一步,快的一次跳两步,往链表末端移动,若慢指针追上了快指针
    ,则说明链表存在环。 此方法速度很快且不需要额外的存储空间。
    bool IsLoop(node *head)
    {
        node *pSlow=head;
        node *pFast=head;
        while(pSlow!=NULL && pFast!=NULL)
        {
            pSlow=pSlow->next;
            pFast=pFast->next->next;
            if(pSlow==pFast)
               return true;
        }
        return false;
    }
    

  • 相关阅读:
    【转】acm小技巧
    poj-1703-Find them, Catch them
    poj-1611-The Suspects
    poj-2236-Wireless Network
    hdu-4496-D-City
    hdu-1213-How Many Tables
    hdu-1856-More is better
    gcd和ex_gcd
    递归趣文
    算法实质【Matrix67】
  • 原文地址:https://www.cnblogs.com/keanuyaoo/p/3315467.html
Copyright © 2011-2022 走看看