温馨提示×

C++单链表如何实现

c++
小樊
84
2024-07-16 20:10:52
栏目: 编程语言

在 C++ 中,可以使用类来实现单链表。下面是一个简单的单链表的实现示例:

#include <iostream>

// 定义链表节点结构
struct Node {
    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 == nullptr) {
            head = newNode;
            return;
        }
        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;
    }
};

int main() {
    LinkedList list;
    list.append(1);
    list.append(2);
    list.append(3);
    list.printList();
    
    return 0;
}

在这个示例中,我们定义了一个 Node 结构来表示链表中的节点,并且定义了一个 LinkedList 类来实现单链表。在 LinkedList 类中,我们实现了添加节点和打印链表元素的方法。在 main 函数中,我们创建了一个链表对象并且测试了添加节点和打印链表元素的功能。

0