Convert a Singly Linked List to an Array in C++

The task is to convert a Singly Linked List to an Array in C++.

A simple example to explain the task can be-

input: 10->20->50->40->35->NULL
output: 10 20 50 40 35

The task will be that the user enters the Linked List and we have to store that Linked List in an Array and print the array.

The approach of the above problem is very simple and can be understood in the following steps-

  1. Make a linked list.
  2. Calculate the length of that linked list.
  3. Make an array of equal length.
  4. Store the linked list using a temporary head.
  5. Print the array.

Below is the implementation of the approach mentioned above-

#include<iostream>
using namespace std;

//create a node class 
class node{
    public:
    node *next;
    int data;
};

//Function to add new elements to the linked list
 node* addnew(int n ){
    node *new1= new node;
    new1->data=n;
    new1->next=NULL;
  return new1;
 }


//Function to print the created array
 void printarra(int *A,int n ){
   for(int i =0;i<n;i++){
    cout<<A[i]<<" ";
 }
 }


//Function to find the length of the linked list
 int findlength(node *head){
    node*temp=head;
    int totallength=0;
    while(temp!=NULL){
    totallength++;
    temp=temp->next;
 }
   return totallength;
 }

//Function to convert the linked list to array and later print it

 void converttoarray(node *head){
   int len =findlength(head);
   int i =0;
   node *temp=head;
   int *A=new int[len];
  while(temp!=NULL){
    A[i++]=temp->data;
    temp=temp->next;
  }

 printarra(A,len);
 }

//Our driver Code
 int main(){

//initialising the linked list with elements
   node *head= NULL;
   head=addnew(10);
   head->next=addnew(20);
   head->next->next=addnew(50);
   head->next->next->next=addnew(40);
   head->next->next->next->next=addnew(35);
//Calling the function which will convert the linkedlist to array amd print it
  converttoarray(head);
  return 0;
 }



The output will be-

10 20 50 40 35

We followed the steps and got the output as we wanted.

You may also want to read the following article.

  1.  Circular Linked List in C++
  2. Search an element in Linked List

Leave a Reply

Your email address will not be published. Required fields are marked *