Convert a Singly Linked List to an Array in Python

In this tutorial, we will learn how a Singly Linked List can be converted to an Array in Python.
Before jumping into the actual topic let’s gain a little knowledge of how both of these data structures work.


What is a Linked List?

A linked list is defined as a data structure that represents a sequence of nodes. In a singly linked list, each node points to the next node via links in the linked list, connected via pointers. As we know that Python does not have a linked list in its library directly, therefore we implement it using the concept of nodes.


What is an Array?

I am sure all of you know what an array is, but just in case if you want to brush up here it is,
An array is a collection of elements stored at adjoining memory locations. It stores multiple items of the same datatype together. Which makes it easier to access the value and to perform operations. The address of only the first element is saved and the value of the rest is calculated via its offset.


Code

Below is the Python code to convert a singly linked list to an array:

#Structure
class node:
    def __init__(self, data):
        self.data=data
        self.next=None

#Func to add new node to the linked list
def add(data):
    nn=node(0)
    nn.data=data
    nn.next=None
    return nn

#to print array contents
def printarray(a,n):
    i=0
    while(i<n):
        print(a[i], end = " ")
        i=i+1

#to find the length of the linked list       
def findlength(head):
    cur=head
    count=0
    while(cur!=None):
        count=count+1
        cur=cur.next
    return count
#to convert linked list to array
def convertarr(head):
    len=findlength(head)
    arr=[]
    index=0
    cur=head
    
    while(cur!=None):
        arr.append(cur.data)
        cur=cur.next
    
    #printing the array which we created    
    printarray(arr, len)

head=node(0)
head=add(6)
head.next = add(4) 
head.next.next = add(3) 
head.next.next.next = add(4) 

convertarr(head) 

In the above code, we are taking each element from the singly linked list from its data part and converting it into its array by placing them in their positions accordingly. The input is done in the same way as that how user enters the value.

Output

6 4 3 4

You can also make this program menu driven by taking the input from the user.

Leave a Reply

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