从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

结论

猜你喜欢