Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++链表

作者:整整ー世♂陰霾そ   发布日期:2025-05-29   浏览:61

#include <iostream>
using namespace std;

// 定义链表节点结构体
struct Node {
    int data;           // 数据域
    Node* next;         // 指针域,指向下一个节点

    // 构造函数,初始化节点
    Node(int val) : data(val), next(nullptr) {}
};

// 定义链表类
class LinkedList {
private:
    Node* head;         // 头指针,指向链表的第一个节点

public:
    // 构造函数,初始化空链表
    LinkedList() : head(nullptr) {}

    // 析构函数,释放链表占用的内存
    ~LinkedList() {
        Node* current = head;
        while (current != nullptr) {
            Node* nextNode = current->next;
            delete current;
            current = nextNode;
        }
    }

    // 在链表头部插入新节点
    void insertAtHead(int value) {
        Node* newNode = new Node(value);
        newNode->next = head;
        head = newNode;
    }

    // 打印链表中的所有元素
    void printList() {
        Node* current = head;
        while (current != nullptr) {
            cout << current->data << " -> ";
            current = current->next;
        }
        cout << "nullptr" << endl;
    }
};

int main() {
    LinkedList list;

    // 插入一些数据到链表中
    list.insertAtHead(3);
    list.insertAtHead(2);
    list.insertAtHead(1);

    // 打印链表
    list.printList();

    return 0;
}

解释说明:

  1. Node 结构体:定义了链表节点,包含两个成员变量:data 用于存储数据,next 用于指向下一个节点。构造函数用于初始化节点。
  2. LinkedList 类:封装了链表的操作,包括插入和打印链表。head 是指向链表第一个节点的指针。
  3. insertAtHead 函数:在链表头部插入一个新节点。
  4. printList 函数:遍历链表并打印每个节点的数据。
  5. main 函数:创建了一个 LinkedList 对象,并插入了一些数据,最后调用 printList 打印链表内容。

这个简单的例子展示了如何使用 C++ 实现一个单向链表的基本操作。

上一篇:c++ for循环

下一篇:c++引用

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

c++ 树

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站