在 C++ 中列印連結列表

Jinku Hu 2023年1月30日 2020年12月31日
  1. 使用自定義函式列印連結列表中的元素
  2. 使用自定義的函式列印連結列表中的所有元素
在 C++ 中列印連結列表

本文將介紹幾種在 C++ 中列印連結列表元素的方法。

使用自定義函式列印連結列表中的元素

在下面的例子中,我們手動構建一個連結列表資料結構,用任意值初始化它,然後將元素列印到控制檯。實現的結構是一個單一的連結列表,有三個資料成員,分別稱為 citycountrykey

函式 addNewNode 用於在連結列表中構造一個新元素。它以 Node* 引數作為構建新節點的地址,以及需要為其資料成員分配的 3 個對應值。

由於我們是手動構建資料結構,我們需要利用動態記憶體分配。因此,在程式退出之前,需要另一個函式 freeNodes 來釋放連結串列。

一旦完成了連結列表的初始化,我們就可以在迴圈中呼叫 printNodeData 函式來列印從 vector 對中推送到列表中的相同數量的元素。該函式只取型別為 Node*的引數,並呼叫 cout 將每個資料成員輸出到控制檯。這個函式的缺點是,使用者每次需要列印元素時,都需要擔心是否正確迭代到連結列表中。

#include<iostream>
#include<string>
#include<vector>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::pair;

struct Node {
    struct Node *next{};
    string city;
    string country;
    int key{};
};

struct Node *addNewNode(struct Node *node, int key, string &city, string &country) {
    node->next = new Node;
    node->next->key = key;
    node->next->city = city;
    node->next->country = country;
    return node;
}

void freeNodes(struct Node *node) {
    struct Node *tmp = nullptr;
    while (node) {
        tmp = node;
        node = node->next;
        delete tmp;
    }
}

void printNodeData(struct Node *node) {
    cout << "key: " << node->key << endl
        << "city: " << node->city << endl
        << "county: " << node->country << endl << endl;
}

int main() {
    struct Node *tmp, *root;
    struct Node *end = nullptr;

    vector<pair<string, string>> list = {{"Tokyo",  "Japan"},
                              {"New York",  "United States"},
                              {"Mexico City",  "Mexico"},
                              {"Tangshan",  "China"},
                              {"Tainan",  "Taiwan"}};

    root = new Node;
    tmp = root;
    for (int i = 0; i < list.size(); ++i) {
        tmp = addNewNode(tmp, i+1, list[i].first, list[i].second);
        tmp = tmp->next;
    }

    tmp = root->next;
    for (const auto &item : list) {
        printNodeData(tmp);
        tmp = tmp->next;
    }

    freeNodes(root->next);
    delete root;

    return EXIT_SUCCESS;
}

輸出:

key: 1
city: Tokyo
county: Japan
...

使用自定義的函式列印連結列表中的所有元素

print 函式更好的實現是隻呼叫一次的函式。printNodes 函式被定義為 void 型別,它不向呼叫者返回任何東西。它正好需要一個型別為 Node*的引數,類似於前面的函式,它自己在連結列表中進行迭代。注意,呼叫 freeNodes 函式還不足以清理資料結構使用的所有動態記憶體。從 main 函式中分配的 root 指標也需要釋放,否則,記憶體洩漏將不可避免。

#include<iostream>
#include<string>
#include<vector>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::pair;

struct Node {
    struct Node *next{};
    string city;
    string country;
    int key{};
};

struct Node *addNewNode(struct Node *node, int key, string &city, string &country) {
    node->next = new Node;
    node->next->key = key;
    node->next->city = city;
    node->next->country = country;
    return node;
}

void freeNodes(struct Node *node) {
    struct Node *tmp = nullptr;
    while (node) {
        tmp = node;
        node = node->next;
        delete tmp;
    }
}

void printNodes(struct Node *node) {
    while (node){
        cout << "key: " << node->key << endl
            << "city: " << node->city << endl
            << "county: " << node->country << endl << endl;
        node = node->next;
    }
}

int main() {
    struct Node *tmp, *root;
    struct Node *end = nullptr;

    vector<pair<string, string>> list = {{"Tokyo",  "Japan"},
                              {"New York",  "United States"},
                              {"Mexico City",  "Mexico"},
                              {"Tangshan",  "China"},
                              {"Tainan",  "Taiwan"}};

    root = new Node;
    tmp = root;
    for (int i = 0; i < list.size(); ++i) {
        tmp = addNewNode(tmp, i+1, list[i].first, list[i].second);
        tmp = tmp->next;
    }

    printNodes(root->next);

    freeNodes(root->next);
    delete root;

    return EXIT_SUCCESS;
}

輸出:

key: 1
city: Tokyo
county: Japan
...
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ List