|
| 1 | +class Node: |
| 2 | + """A node in a singly linked list.""" |
| 3 | + |
| 4 | + def __init__(self, data: int = 0): |
| 5 | + self.data = data # The value of the node |
| 6 | + self.next = None # Pointer to the next node |
| 7 | + |
| 8 | + |
| 9 | +def array_to_linked_list(arr: list[int]) -> Node: |
| 10 | + """ |
| 11 | + Convert an array into a linked list. |
| 12 | +
|
| 13 | + :param arr: List of integers to convert into a linked list. |
| 14 | + :return: The head of the linked list. |
| 15 | +
|
| 16 | + >>> array_to_linked_list([1, 2, 3]) |
| 17 | + Node(data=1, next=Node(data=2, next=Node(data=3, next=None))) |
| 18 | + >>> array_to_linked_list([]) |
| 19 | + >>> array_to_linked_list([4, 5, 6]) |
| 20 | + Node(data=4, next=Node(data=5, next=Node(data=6, next=None))) |
| 21 | + """ |
| 22 | + if arr is None: # Check for empty array |
| 23 | + return None |
| 24 | + |
| 25 | + # Create the head of the linked list |
| 26 | + head = Node(arr[0]) |
| 27 | + n = head # Pointer to the current node |
| 28 | + |
| 29 | + # Loop through the array and construct the linked list |
| 30 | + for data in arr[1:]: |
| 31 | + n.next = Node(data) # Create a new node and link it |
| 32 | + n = n.next # Move to the next node |
| 33 | + |
| 34 | + return head # Return the head of the linked list |
| 35 | + |
| 36 | + |
| 37 | +# Example usage |
| 38 | +if __name__ == "__main__": |
| 39 | + # Input: a list of integers |
| 40 | + input_array = list(map(int, input("Enter array elements separated by space: ").strip().split())) |
| 41 | + linked_list_head = array_to_linked_list(input_array) |
| 42 | + |
| 43 | + |
| 44 | + # Function to print the linked list for demonstration |
| 45 | + def print_linked_list(head: Node): |
| 46 | + """Print the linked list.""" |
| 47 | + n = head |
| 48 | + while n is not None: |
| 49 | + print(n.data, end=" -> ") |
| 50 | + n = n.next |
| 51 | + print("None") |
| 52 | + |
| 53 | + |
| 54 | + # Print the resulting linked list |
| 55 | + print_linked_list(linked_list_head) |
0 commit comments