c++写个循环单链表
时间: 2023-11-18 10:52:32 浏览: 85
以下是C++实现循环单链表的代码:
```c++
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}
void insert(int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
head->next = head;
}
else {
Node* temp = head;
while (temp->next != head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = head;
}
}
void display() {
if (head == NULL) {
cout << "List is empty" << endl;
}
else {
Node* temp = head;
do {
cout << temp->data << " ";
temp = temp->next;
} while (temp != head);
cout << endl;
}
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.display();
return 0;
}
```
阅读全文