Create linked list from a given array in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to learn how to create a linked list from the given array.

Let's see the steps to solve the problem.

  • Initialize the array with dummy data.

  • Write the struct node.

  • Iterate over the array.

    • Create a new node with the data.

    • Insert the new node into the linked list.

  • Print the linked list.

Example

Let's see the code.

#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;
}

Output

If you run the above code, then you will get the following result.

1 -> 2 -> 3 -> 4 -> 5 -> NULL

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 28-Jan-2021 11:33:21
Advertisements