对一个链表判断是否有环

目前能想到的是两种:一:在遍历的同时对其节点进行存储(存储方式多样);

                                    二:设定两个指针(变量),利用速度(遍历快慢)差,进行判断。

一:采用容器unordered_set ,进行存储;(set为集合即不能插入相同的)

关于容器unordered_set;

https://blog.csdn.net/qq_32172673/article/details/85160180

bool Set_Cirlist(ListNode*head){
    unordered_set Lset;
    while(head!=nullptr){    //  当头指针不为空时执行
      if(Lset.count(head)){            //count函数返回相同元素个数
         return true;    //即在Lset中存在相同的元素 返回true            
        }
      Lset.insert(head); //插入数据
      head=head->next;  //指针向后移动;
    }
    return false;
}

二:设定两个指针变量。

对于两个指针变量Fpos,Spos;对于两个有速度差的量,如果重逢,便存在环;

bool Speed_Cirlist(ListNode*head){
    if(head==nullptr||head->next==nullptr) //为空时,以及一个元素时
        return false;
    ListNode*Fpos=head;
    ListNode*Spos=head->next;
    while(Fpos!=Spos){
        if(Spos == nullptr || Spos->next==nullptr)        //添加判断
            return false;
        Fpos=Fpos->next;
        Spos=Spos->next->next; //那么后面第二个是否存在/或者为空,即->next、->next->next后是否为空,便需要在前面添加判断
    }
    return true;
}

 

你可能感兴趣的:(数据结构,与算法)