Convert a Singly Linked List to an array

24 Mar, 2022
Given a singly linked list and the task is to convert it into an array.Examples:  
Input: List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 2 3 4 5Input: List = 10 -> 20 -> 30 -> 40 -> 50 -> NULL Output: 10 20 30 40 50  
 
Approach: An approach to creating a linked list from the given array has been discussed in this article. Here, an approach to convert the given linked list to an array will be discussed.  
Find the length of the given linked list say len.
Create an array of size len.
Traverse the given linked list and store the elements in the array one at a time.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <iostream>using namespace std; // Singly Linked List structurestruct node {    int data;    node* next;}; // Function to add a new node// to the Linked Listnode* add(int data){    node* newnode = new node;    newnode->data = data;    newnode->next = NULL;    return newnode;} // Function to print the array contentsvoid printArr(int a[], int n){    for (int i = 0; i < n; i++)        cout << a[i] << " ";} // Function to return the length// of the Linked Listint findlength(node* head){    node* curr = head;    int cnt = 0;    while (curr != NULL) {        cnt++;        curr = curr->next;    }    return cnt;} // Function to convert the// Linked List to an arrayvoid convertArr(node* head){     // Find the length of the    // given linked list    int len = findlength(head);     // Create an array of the    // required length    int arr[len];     int index = 0;    node* curr = head;     // Traverse the Linked List and add the    // elements to the array one by one    while (curr != NULL) {        arr[index++] = curr->data;        curr = curr->next;    }     // Print the created array    printArr(arr, len);} // Driver codeint main(){    node* head = NULL;    head = add(1);    head->next = add(2);    head->next->next = add(3);    head->next->next->next = add(4);    head->next->next->next->next = add(5);     convertArr(head);     return 0;}
// Java implementation of the approachclass GFG{ // Singly Linked List structurestatic class node{    int data;    node next;} // Function to add a new node// to the Linked Liststatic node add(int data){    node newnode = new node();    newnode.data = data;    newnode.next = null;    return newnode;} // Function to print the array contentsstatic void printArr(int a[], int n){    for (int i = 0; i < n; i++)        System.out.print(a[i]+" ");} // Function to return the length// of the Linked Liststatic int findlength(node head){    node curr = head;    int cnt = 0;    while (curr != null)    {        cnt++;        curr = curr.next;    }    return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){     // Find the length of the    // given linked list    int len = findlength(head);     // Create an array of the    // required length    int []arr = new int[len];     int index = 0;    node curr = head;     // Traverse the Linked List and add the    // elements to the array one by one    while (curr != null)    {        arr[index++] = curr.data;        curr = curr.next;    }     // Print the created array    printArr(arr, len);} // Driver codepublic static void main(String []args){    node head = new node();    head = add(1);    head.next = add(2);    head.next.next = add(3);    head.next.next.next = add(4);    head.next.next.next.next = add(5);     convertArr(head);}} // This code is contributed by Rajput-Ji
# Python3 implementation of the approach # Structure of a Nodeclass node:    def __init__(self, data):        self.data = data        self.next = None # Function to add a new node# to the Linked Listdef add(data):     newnode = node(0)    newnode.data = data    newnode.next = None    return newnode # Function to print the array contentsdef printArr(a, n):     i = 0    while(i < n):        print (a[i], end = " ")        i = i + 1 # Function to return the length# of the Linked Listdef findlength( head):     curr = head    cnt = 0    while (curr != None):             cnt = cnt + 1        curr = curr.next         return cnt # Function to convert the# Linked List to an arraydef convertArr(head):     # Find the length of the    # given linked list    len1 = findlength(head)     # Create an array of the    # required length    arr = []     index = 0    curr = head     # Traverse the Linked List and add the    # elements to the array one by one    while (curr != None):        arr.append( curr.data)        curr = curr.next         # Print the created array    printArr(arr, len1) # Driver codehead = node(0)head = add(1)head.next = add(2)head.next.next = add(3)head.next.next.next = add(4)head.next.next.next.next = add(5)convertArr(head) # This code is contributed by Arnab kundu
// C# implementation of the approachusing System;                     class GFG{ // Singly Linked List structurepublic class node{    public int data;    public node next;} // Function to add a new node// to the Linked Liststatic node add(int data){    node newnode = new node();    newnode.data = data;    newnode.next = null;    return newnode;} // Function to print the array contentsstatic void printArr(int []a, int n){    for (int i = 0; i < n; i++)        Console.Write(a[i] + " ");} // Function to return the length// of the Linked Liststatic int findlength(node head){    node curr = head;    int cnt = 0;    while (curr != null)    {        cnt++;        curr = curr.next;    }    return cnt;} // Function to convert the// Linked List to an arraystatic void convertArr(node head){     // Find the length of the    // given linked list    int len = findlength(head);     // Create an array of the    // required length    int []arr = new int[len];     int index = 0;    node curr = head;     // Traverse the Linked List and add the    // elements to the array one by one    while (curr != null)    {        arr[index++] = curr.data;        curr = curr.next;    }     // Print the created array    printArr(arr, len);} // Driver codepublic static void Main(String []args){    node head = new node();    head = add(1);    head.next = add(2);    head.next.next = add(3);    head.next.next.next = add(4);    head.next.next.next.next = add(5);     convertArr(head);}} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the approach // Singly Linked List structureclass node {        constructor() {                this.data = 0;                this.next = null;             }        }         // Function to add a new node// to the Linked Listfunction add( data){    var newnode = new node();    newnode.data = data;    newnode.next = null;    return newnode;} // Function to print the array contentsfunction printArr( a,  n){    for (let i = 0; i < n; i++)        document.write(a[i]+" ");} // Function to return the length// of the Linked Listfunction findlength( head){    var curr = head;    let cnt = 0;    while (curr != null)    {        cnt++;        curr = curr.next;    }    return cnt;} // Function to convert the// Linked List to an arrayfunction convertArr( head){     // Find the length of the    // given linked list    let len = findlength(head);     // Create an array of the    // required length    let arr = new Array(len);         let index = 0;    var curr = head;     // Traverse the Linked List and add the    // elements to the array one by one    while (curr != null)    {        arr[index++] = curr.data;        curr = curr.next;    }     // Print the created array    printArr(arr, len);} // Driver Code var head = new node();head = add(1);head.next = add(2);head.next.next = add(3);head.next.next.next = add(4);head.next.next.next.next = add(5); convertArr(head);     </script>
1 2 3 4 5
 
Time Complexity: O(N)Auxiliary Space: O(N)
Rajput-Ji
29AjayKumar
andrew1234
jana_sayantan
pankajsharmagfg
surinderdawra388
Algorithms
Arrays
Linked List
Technical Scripter
Linked List
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Largest Sum Contiguous Subarray
Arrays in C/C++