Convert an Array into Linked List in Python

 Convert  an Array into Linked List in Python




Code

class Node:

    def __init__(self, value):

        self.value = value

        self.next = None


def array_to_linked_list(arr):

    """

    Converts an array into a linked list.


    Args:

    - arr (list): The input array.


    Returns:

    - Node: The head of the linked list.

    """

    if not arr:

        return None

    

    head = Node(arr[0])

    current = head

    for value in arr[1:]:

        current.next = Node(value)

        current = current.next

    

    return head


# Example usage

arr = [1, 2, 3, 4, 5]

head = array_to_linked_list(arr)


# Print the input array

print("Input Array:", arr)


# Print the linked list

linked_list_values = []

current = head

while current:

    linked_list_values.append(current.value)

    current = current.next


print("Linked List:", linked_list_values)



Explanation:

  • We define a Node class to represent each element of the linked list. Each node has a value attribute to store the value and a next attribute to point to the next node in the list.
  • The array_to_linked_list function takes an array (arr) as input and returns the head of the linked list created from the array.
  • We iterate over the input array and create a node for each element. We connect these nodes to form a linked list.
  • Finally, we print the input array and the values of the linked list to demonstrate the conversion




Post a Comment

0 Comments