溫馨提示×

c++鏈表怎么實現

c++
小億
105
2024-08-01 18:00:12
欄目: 編程語言

在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函數中創建一個鏈表對象,插入幾個節點并打印鏈表內容。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女