拍摄集

新澳免费资料网站大全056期_手机app官方版免费安装下载

单链表是一种常见的线性表数据结构,它由节点组成,每个节点包含数据和一个指向下一个节点的指针。以下是一个简单的C++实现:

#include <iostream>

// 节点类
class Node {
public:
    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) {
            head = newNode;
            return;
        }

        Node* current = head;
        while (current->next) {
            current = current->next;
        }

        current->next = newNode;
    }

    // 在链表头部插入元素
    void prepend(int value) {
        Node* newNode = new Node(value);
        newNode->next = head;
        head = newNode;
    }

    // 打印链表元素
    void print() const {
        Node* current = head;
        while (current) {
            std::cout << current->data << " ";
            current = current->next;
        }
        std::cout << std::endl;
    }

    // 析构函数,释放节点内存
    ~LinkedList() {
        Node* current = head;
        while (current) {
            Node* next = current->next;
            delete current;
            current = next;
        }
        head = nullptr;
    }
};

int main() {
    LinkedList list;

    list.append(1);
    list.append(2);
    list.append(3);

    list.print();

    list.prepend(0);

    list.print();

    return 0;
}

这个简单的实现包括一个类表示节点,以及一个类表示单链表。可以使用在链表末尾添加元素,使用在链表头部插入元素,使用打印链表的元素。在程序的函数中,创建了一个链表并添加了一些元素,然后打印了链表。


2020年01期四不像必中一肖 今晚开一肖特马图

相关推荐