C++实现线性表-单链表
作者:野牛程序员:2023-12-05 09:23:27 C++阅读 2989
单链表是一种常见的线性表数据结构,它由节点组成,每个节点包含数据和一个指向下一个节点的指针。以下是一个简单的C++实现:
#include <iostream>
// 节点类
class Node {
public:
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) {
head = newNode;
return;
}
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
// 在链表头部插入元素
void prepend(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}
// 打印链表元素
void print() const {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
// 析构函数,释放节点内存
~LinkedList() {
Node* current = head;
while (current) {
Node* next = current->next;
delete current;
current = next;
}
head = nullptr;
}
};
int main() {
LinkedList list;
list.append(1);
list.append(2);
list.append(3);
list.print();
list.prepend(0);
list.print();
return 0;
}这个简单的实现包括一个Node类表示节点,以及一个LinkedList类表示单链表。可以使用append在链表末尾添加元素,使用prepend在链表头部插入元素,使用print打印链表的元素。在程序的main函数中,创建了一个链表并添加了一些元素,然后打印了链表。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

