C++中使用类来完成对链表的构造
时间: 2024-01-08 22:03:54 浏览: 32
以下是使用类来构造链表的示例代码:
```c++
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = NULL;
}
};
class LinkedList {
public:
Node* head;
LinkedList() {
this->head = NULL;
}
void insert(int data) {
Node* newNode = new Node(data);
if (this->head == NULL) {
this->head = newNode;
} else {
Node* current = this->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void printList() {
Node* current = this->head;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
list.insert(1);
list.insert(2);
list.insert(3);
list.printList();
return 0;
}
```
在上面的示例代码中,我们首先定义了一个 `Node` 类,用于表示链表中的节点。该类包含一个 `data` 属性,表示节点中存储的数据,以及一个 `next` 属性,表示指向下一个节点的指针。
接下来,我们定义了一个 `LinkedList` 类,用于表示整个链表。该类包含一个 `head` 属性,表示链表的头节点。
在 `LinkedList` 类中,我们实现了 `insert` 方法,用于将数据插入到链表中。该方法会创建一个新的 `Node` 对象,并将其插入到链表的末尾。
我们还实现了 `printList` 方法,用于打印链表中的所有数据。
在 `main` 函数中,我们创建了一个 `LinkedList` 对象,并向其中插入了三个数据。最后,我们调用 `printList` 方法,打印整个链表的数据。