c++链表类
时间: 2023-07-04 22:04:25 浏览: 57
以下是一个简单的C++链表类的示例代码:
```
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
class LinkedList {
public:
Node* head;
LinkedList() {
head = NULL;
}
void addNode(int value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList() {
Node* current = head;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
}
};
int main() {
LinkedList list;
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.printList();
return 0;
}
```
这个 LinkedList 类包含两个嵌套类:Node 和 LinkedList。Node 类表示链表中的节点,包含一个整数数据和一个指向下一个节点的指针。LinkedList 类包含一个指向链表头部的指针 head,以及添加节点和打印链表的方法 addNode 和 printList。我们可以在 main 函数中创建一个 LinkedList 对象,并使用 addNode 方法添加节点,最后使用 printList 方法打印链表。