C++ 链表
时间: 2023-07-03 11:14:13 浏览: 47
C++ 中链表可以通过定义结构体或类来实现。以下是一个使用结构体实现链表的示例:
```cpp
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
class LinkedList {
private:
Node* head;
public:
LinkedList() {
head = NULL;
}
void add(int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
}
else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
void print() {
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.add(1);
list.add(2);
list.add(3);
list.print();
return 0;
}
```
这个示例使用了结构体 Node 和类 LinkedList,其中 Node 存储链表中的值和下一个节点的指针,LinkedList 存储链表头指针和链表操作方法。在主函数中,我们首先创建了一个空的链表 list,然后通过 add 方法向链表中添加了三个值,最后通过 print 方法打印链表中的所有值。