Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions data_structures/linked_list/arr_to_ll.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class Node:
"""A node in a singly linked list."""

def __init__(self, data: int = 0):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide return type hint for the function: __init__. If the function does not return a value, please provide the type hint as: def function() -> None:

self.data = data # The value of the node
self.next = None # Pointer to the next node


def array_to_linked_list(arr: list[int]) -> Node:
"""
Convert an array into a linked list.

:param arr: List of integers to convert into a linked list.
:return: The head of the linked list.

>>> array_to_linked_list([1, 2, 3])
Node(data=1, next=Node(data=2, next=Node(data=3, next=None)))
>>> array_to_linked_list([])
>>> array_to_linked_list([4, 5, 6])
Node(data=4, next=Node(data=5, next=Node(data=6, next=None)))
"""
if arr is None: # Check for empty array
return None

# Create the head of the linked list
head = Node(arr[0])
n = head # Pointer to the current node

# Loop through the array and construct the linked list
for data in arr[1:]:
n.next = Node(data) # Create a new node and link it
n = n.next # Move to the next node

return head # Return the head of the linked list


# Example usage
if __name__ == "__main__":
# Input: a list of integers
input_array = list(map(int, input("Enter array elements separated by space: ").strip().split()))

Check failure on line 40 in data_structures/linked_list/arr_to_ll.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

data_structures/linked_list/arr_to_ll.py:40:89: E501 Line too long (100 > 88)
linked_list_head = array_to_linked_list(input_array)


# Function to print the linked list for demonstration
def print_linked_list(head: Node):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/linked_list/arr_to_ll.py, please provide doctest for the function print_linked_list

Please provide return type hint for the function: print_linked_list. If the function does not return a value, please provide the type hint as: def function() -> None:

"""Print the linked list."""
n = head
while n is not None:
print(n.data, end=" -> ")
n = n.next
print("None")


# Print the resulting linked list
print_linked_list(linked_list_head)
Loading