在C++中,如何实现一个简单的链表数据结构?c++中链表的用法

在C++中,如何实现一个简单的链表数据结构? c++中链表的用法

在C++中,你可以使用结构体和指针来实现一个简单的链表数据结构。以下是一个简单的示例:

struct Node {    int data;    Node* next;};class LinkedList {public:    LinkedList() : head(nullptr) {}    void insert(int value) {        Node* newNode = new Node();        newNode->data = value;        newNode->next = nullptr;        if (head == nullptr) {            head = newNode;        } else {            Node* current = head;            while (current->next != nullptr) {                current = current->next;            }            current->next = newNode;        }    }    void printList() {        Node* current = head;        while (current != nullptr) {            std::cout << current->data << " ";            current = current->next;        }        std::cout << std::endl;    }private:    Node* head;};

在这个代码中,我们定义了一个名为Node的结构体,它有两个成员:一个用于存储数据的int型变量data和一个指向下一个节点的指针next。然后我们定义了一个名为LinkedList的类,它有一个私有成员head,表示链表的头节点。LinkedList类有两个公开的成员函数:insert用于向链表中插入新的元素,printList用于打印链表中的所有元素。

na.png

本网站文章未经允许禁止转载,合作/权益/投稿 请联系平台管理员 Email:epebiz@outlook.com