下面是一个链表构建和显示的C++完整可运行程序:

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

Node* createList(int arr[], int n) {
    Node* head = NULL;
    Node* tail = NULL;
    for (int i = 0; i < n; i++) {
        Node* newNode = new Node;
        newNode->data = arr[i];
        newNode->next = NULL;
        if (head == NULL) {
            head = newNode;
            tail = newNode;
        }
        else {
            tail->next = newNode;
            tail = newNode;
        }
    }
    return head;
}

void printList(Node* head) {
    Node* curr = head;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
    cout << endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    Node* head = createList(arr, 5);
    printList(head);
    return 0;
}

这个程序中,我们首先定义了一个Node结构体,用于表示链表中的节点。然后,我们定义了两个函数,一个用于创建链表,另一个用于打印链表。在createList函数中,我们遍历输入的数组,为每个元素创建一个新的节点,并将它们按顺序链接起来。在printList函数中,我们遍历链表,打印每个节点的数据。

main函数中,我们创建一个整数数组,然后调用createList函数来创建链表。最后,我们调用printList函数来打印链表的内容。

写一个链表构建和显示的c++完整可运行程序

原文地址: https://www.cveoy.top/t/topic/bhsg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录