#include 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/mJdN 著作权归作者所有。请勿转载和采集!

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