在 C++ 中檢查連結串列是否為迴圈連結串列
在本文中,我們將學習如何檢查連結串列是否為迴圈連結串列。若要檢查連結串列是否迴圈,我們將儲存頭節點到某個其他變數中,然後遍歷列表,如果在任意節點的 next 部分獲得 null,那麼它就不迴圈,否則,我們將檢查 next 節點是否與儲存節點相同,如果是,那麼它就是迴圈的。
示例
#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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP