ในที่นี้เราจะดูว่า จอบ เช็คลิงค์ลิสต์เป็นวงกลมหรือเปล่า เพื่อตรวจสอบว่ารายการที่เชื่อมโยงเป็นวงกลมหรือไม่ เราจะเก็บโหนดส่วนหัวไว้ในตัวแปรอื่น จากนั้นข้ามรายการ หากเราได้รับค่าว่างที่ส่วนถัดไปของโหนดใดๆ โหนดนั้นจะไม่เป็นวงกลม มิฉะนั้น เราจะตรวจสอบ โหนดถัดไปจะเหมือนกับโหนดที่เก็บไว้หรือไม่ ถ้าใช่ โหนดถัดไปจะเป็นโหนดแบบวงกลม
ตัวอย่าง
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
};
Node* getNode(int data){
Node *newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
bool isCircularList(Node *start){
if(start == NULL)
return true;
Node *node = start->next;
while(node != NULL && node != start){
node = node->next;
}
if(node == start)
return true;
return false;
}
int main() {
Node *start = getNode(10);
start->next = getNode(20);
start->next->next = getNode(30);
start->next->next->next = getNode(40);
start->next->next->next->next = getNode(50);
start->next->next->next->next->next = start;
if (isCircularList(start))
cout << "The list is circular list";
else
cout << "The list is not circular list";
} ผลลัพธ์
The list is circular list