C++的STL循环链表
时间: 2024-05-12 14:10:49 浏览: 23
C++的STL(Standard Template Library)中没有提供循环链表(circular linked list)的标准容器。STL提供了其他常用的容器,如vector、list、deque等,但没有直接支持循环链表。
如果你需要使用循环链表,可以自己实现或使用第三方库。循环链表是一种链表的变体,它的最后一个节点指向第一个节点,形成一个闭环。你可以通过定义一个节点结构体或类来表示链表的节点,然后使用指针将它们连接起来。
以下是一个简单的循环链表的示例代码:
```cpp
#include <iostream>
struct Node {
int data;
Node* next;
};
class CircularLinkedList {
private:
Node* head;
public:
CircularLinkedList() {
head = nullptr;
}
void insert(int value) {
Node* newNode = new Node;
newNode->data = value;
if (head == nullptr) {
head = newNode;
newNode->next = head;
} else {
Node* temp = head;
while (temp->next != head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = head;
}
}
void display() {
if (head == nullptr) {
std::cout << "Circular Linked List is empty." << std::endl;
return;
}
Node* temp = head;
do {
std::cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
std::cout << std::endl;
}
};
int main() {
CircularLinkedList cll;
cll.insert(1);
cll.insert(2);
cll.insert(3);
cll.display();
return 0;
}
```
上述代码定义了一个循环链表类`CircularLinkedList`,其中包含了插入节点和显示链表内容的方法。在`main`函数中,我们创建了一个循环链表对象`cll`,并插入了三个节点,然后调用`display`方法显示链表内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)