C++数据结构
单向链表
//
// Created by 19342 on 2024/9/14.
//
#include <iostream>
using namespace std;// 定义链表节点
struct Node {int data; // 节点存储的数据Node* next; // 指向下一个节点的指针
};// 初始化链表
Node* initList() {return nullptr;
}// 在链表末尾添加一个新节点
void append(Node*& head, int value) {Node* newNode = new Node();newNode->data = value;newNode->next = nullptr;if (head == nullptr) { // 如果链表为空head = newNode;} else {Node* temp = head;while (temp->next != nullptr) { // 移动到链表的最后一个节点temp = temp->next;}temp->next = newNode; // 将新节点附加到最后}
}// 打印链表的所有元素
void printList(const Node* head) {const Node* temp = head;while (temp != nullptr) {cout << temp->data << " ";temp = temp->next;}cout << endl;
}int main() {Node* head = initList(); // 创建空链表// 向链表中添加一些元素append(head, 1);append(head, 2);append(head, 3);// 打印链表printList(head); // 输出应该是: 1 2 3// 清理内存while (head != nullptr) {Node* temp = head;head = head->next;delete temp; // 释放每个节点占用的内存}return 0;
}
为了防止内存泄漏,我们在主函数中释放了链表中每个节点所分配的内存。