C++实现list链表数据结构
作者:野牛程序员:2023-12-28 11:22:57 C++阅读 2663
C++中可以使用指针和结构体来实现简单的链表数据结构。以下是一个基本的示例代码:
#include <iostream>
// 定义链表节点
struct Node {
int data;
Node* next;
// 构造函数
Node(int value) : data(value), next(nullptr) {}
};
// 定义链表类
class LinkedList {
private:
Node* head;
public:
// 构造函数
LinkedList() : head(nullptr) {}
// 在链表尾部添加元素
void append(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// 在链表头部添加元素
void prepend(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}
// 打印链表元素
void print() {
Node* current = head;
while (current != nullptr) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
// 析构函数释放内存
~LinkedList() {
Node* current = head;
Node* nextNode;
while (current != nullptr) {
nextNode = current->next;
delete current;
current = nextNode;
}
}
};
int main() {
// 创建链表并进行操作
LinkedList myList;
myList.append(1);
myList.append(2);
myList.prepend(0);
myList.print();
return 0;
}此代码演示了如何定义一个简单的链表结构,包括在链表尾部和头部添加元素,以及打印链表元素。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

