從一個給定的陣列建立 C++ 程式中的連結串列
在此教程中,我們將學習如何從給定的 陣列 建立一個 連結串列。
讓我們看看解決此問題所需的步驟。
使用虛擬資料初始化陣列。
編寫結構節點。
迭代陣列。
使用資料建立一個新節點。
將新節點插入連結串列。
列印連結串列。
示例
讓我們看看程式碼。
#include <bits/stdc++.h> using namespace std; struct Node { int data; Node* next; }; struct Node* newNode(int data) { Node* node = new Node; node->data = data; node->next = NULL; return node; } void insertNewNode(Node** root, int data) { Node* node = newNode(data); Node* ptr; if (*root == NULL) { *root = node; } else { ptr = *root; while (ptr->next != NULL) { ptr = ptr->next; } ptr->next = node; } } void printLinkedList(Node* root) { while (root != NULL) { cout << root->data << " -> "; root = root->next; } cout << "NULL" << endl; } Node* createLinkedList(int arr[], int n) { Node *root = NULL; for (int i = 0; i < n; i++) { insertNewNode(&root, arr[i]); } return root; } int main() { int arr[] = { 1, 2, 3, 4, 5 }, n = 5; Node* root = createLinkedList(arr, n); printLinkedList(root); return 0; }
輸出
如果您執行上述程式碼,則將獲得以下結果。
1 -> 2 -> 3 -> 4 -> 5 -> NULL
結論
如果您對本教程有任何疑問,請在評論部分中提及。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP