If there are two head node pointers, one to go fast, one to walk slowly, then after a few steps, the fast pointer will always go over the slow pointer one lap.
BOOL Iscyclelist (listnode* phead) {if (phead== null) return false;if (Phead->m_pnext = = null) {return false;} listnode* Pfastnode = phead; listnode* Pslownode = phead;//If it is an even number, pfastnode->m_pnext->m_pnext is empty; if it is odd, pfast->m_pnext is empty; while ( Pfastnode->m_pnext! = NULL && Pfastnode->m_pnext->m_pnext! = null) {Pfastnode = pfastnode->m_pnext- >m_pnext;pslownode = pslownode->m_pnext;if (Pslownode = = Pfastnode) {break;}} if (Pfastnode = = NULL | | pfastnode->m_pnext = = NULL) {return false;} Else{return true;}}
Complete code test:
CycleList.cpp: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>using namespace std;struct listnode {int m_nvalue; listnode* M_pnext; ListNode (int k): M_nvalue (k), M_pnext (NULL) {}};bool iscyclelist (listnode* phead) {if (phead== NULL) return false;if ( Phead->m_pnext = = NULL) {return false;} listnode* Pfastnode = Phead; listnode* Pslownode = phead;//If it is an even number, pfastnode->m_pnext->m_pnext is empty; if it is odd, pfast->m_pnext is empty; while ( Pfastnode->m_pnext! = NULL && Pfastnode->m_pnext->m_pnext! = null) {Pfastnode = pfastnode->m_pnext- >m_pnext;pslownode = pslownode->m_pnext;if (Pslownode = = Pfastnode) {break;}} if (Pfastnode = = NULL | | pfastnode->m_pnext = = NULL) {return false;} Else{return true;}} int _tmain (int argc, _tchar* argv[]) {listnode* head = new ListNode (1); listnode* Node1 = new ListNode (2); listnode* Node2 = new ListNode (3); listnode* Node3 = new ListNode (4); listnode* Node4 = new ListNode (5); listnode* NODE5 = new ListNode (6); listnode* Node6 = new LisTnode (7); head->m_pnext = Node1; Node1->m_pnext = Node2; Node2->m_pnext = Node3; Node3->m_pnext = Node4; Node4->m_pnext = NODE5; Node5->m_pnext = Node6; Node6->m_pnext = Head;bool B = iscyclelist (head); Cout<<b<<endl;getchar (); return 0;}
Whether the C + + algorithm is a circular linked list