c++链表怎么实现

   2024-10-02 5090
核心提示:在C++中,链表可以通过定义一个结构体来实现。#include iostream// 定义节点结构体struct Node {int data;Node* next;Node(int v

在C++中,链表可以通过定义一个结构体来实现。

#include <iostream>// 定义节点结构体struct Node {    int data;    Node* next;        Node(int val) : data(val), next(nullptr) {}};// 定义链表类class LinkedList {private:    Node* head;public:    // 构造函数    LinkedList() : head(nullptr) {}    // 插入节点    void insert(int val) {        Node* newNode = new Node(val);        if (head == nullptr) {            head = newNode;        } else {            Node* current = head;            while (current->next != nullptr) {                current = current->next;            }            current->next = newNode;        }    }    // 打印链表    void print() {        Node* current = head;        while (current != nullptr) {            std::cout << current->data << " ";            current = current->next;        }        std::cout << std::endl;    }};int main() {    LinkedList list;    list.insert(1);    list.insert(2);    list.insert(3);    list.print();    return 0;}

以上代码实现了一个简单的单链表,包括插入节点和打印链表的功能。通过定义结构体Node表示链表节点,然后在链表类LinkedList中实现插入节点和打印链表的方法。在main函数中创建一个链表对象,插入几个节点并打印链表内容。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号