单链表中是否有环

    xiaoxiao2021-03-25  141

    #include<iostream> using namespace std; struct ListNode{ int m; ListNode *next; }; ListNode *Creat () { ListNode *pHead = nullptr; ListNode *p1,*p2; p1 = new ListNode; cout<<"Please Enter a Number:"<<endl; cin>>p1->m; while(p1->m != 0) { if(pHead == nullptr) { pHead = p1; p2 = p1; } else { p2->next = p1; p2 = p1; } p1 = new ListNode; cout<<"Please Enter a Number:"<<endl; cin>>p1->m; } p2->next = nullptr; return pHead; } void print(ListNode *pHead) { ListNode *p = pHead; while(p != nullptr) { cout<< p->m<< "\t"; p = p->next; } cout<<endl; } bool Hascircle(ListNode *Head) { ListNode *pfast = Head; ListNode *pslow = Head; while(pfast!=nullptr && pfast->next!=nullptr) { pfast = pfast->next->next; pslow = pslow->next; if (pfast == pslow) return true; } return false; } int main () { ListNode *Head; Head = Creat(); cout<<"The ListNode is"<<endl; print(Head); bool h; h = Hascircle(Head); if(h == true) cout<<"Have a circle."<<endl; else cout<<"Have no circle."<<endl; }
    转载请注明原文地址: https://ju.6miu.com/read-5163.html

    最新回复(0)