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-
- Make a linked list.
- Calculate the length of that linked list.
- Make an array of equal length.
- Store the linked list using a temporary head.
- 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.
Leave a Reply