判断一个单链表是否是环

设置两个指针,一个每次前进两步,一个前进一步,如果存在环,快的指针最终总是能追上慢的指针。如果不存在快指针会比慢指针先指向nullptr

(可以类比操场跑步时速度快与速度慢的两个人总会相遇)

文中代码只是为了测试是否为环,没有进行内存释放。

#include<iostream>
#include<cassert>
struct SList{
    SList *next;
    int value;
};
inline bool isCircle(SList *head){//判断链表是否是成环状的
    
    assert(head);
    auto fast=head;
    auto slow=head;
    while(fast&&fast->next){
        fast=fast->next->next;
        slow=slow->next;
        if(slow==fast)
        break;
    }
    return !((fast==nullptr)||fast->next==nullptr);
}

void testList(){
    SList *next=nullptr;
    SList *current=nullptr;
    SList*start=nullptr;
    for(int i=0;i<10;++i)
    {
        current=new SList;
        current->next=next;
        current->value=i;
        next=current;
        
    }
    if(!start)
        start=current;
    
    auto cir=isCircle(start);//cir should be false
    std::cout <<cir<<std::endl;
    next=nullptr;
    current=nullptr;
    start=nullptr;
    SList *last=nullptr;
    
    for(int i=0;i<3;++i)
    {
        current=new SList;
        current->next=next;
        current->value=i;
        next=current;
        if(!last)
        last=current;
    }
    if(!start)start=current;
    if(last)last->next=start;
    cir=isCircle(start);//cir should be true
    std::cout <<cir<<std::endl;
}

int main(int argc, char* argv[])
{
    testList();
    return 0;
}

 

posted @ 2018-08-28 14:21  快第三个十年  阅读(148)  评论(0编辑  收藏  举报