Skip to content

Commit e18a95b

Browse files
committed
Added type hints to Node class and remove function
1 parent fba1c5d commit e18a95b

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,58 @@
11
class Node:
22
def __init__(self, val):
33
self.val = val
4-
self.next = None
4+
self.next = None # Specify that next can be a Node or None
55

66

7-
def remove(head, n):
7+
def remove(head: Node, n: int) -> Node:
8+
if head is None:
9+
return None # If the head is None, return None
10+
11+
# Create a dummy node that points to the head
812
extra = Node(0)
913
extra.next = head
10-
fast = extra
11-
slow = extra
14+
fast = extra # Make sure fast can be None
15+
slow = extra # Make sure slow can be None
16+
17+
# Move fast ahead by n nodes
1218
for _ in range(n):
13-
fast = fast.next
19+
if fast is not None:
20+
fast = fast.next
1421

15-
while fast.next:
22+
# Move until fast reaches the end
23+
while fast is not None and fast.next is not None:
1624
fast = fast.next
1725
slow = slow.next
1826

19-
slow.next = slow.next.next
27+
# Remove the nth node from the end
28+
if slow is not None and slow.next is not None:
29+
slow.next = slow.next.next # Link slow to the next of the node to be deleted
2030

21-
return extra.next
31+
return extra.next # Return the new head, which may be None if the list is empty
2232

2333

2434
def print_list(head: Node) -> None:
2535
curr = head
26-
while curr:
36+
while curr is not None:
2737
print(curr.val, end=" ")
2838
curr = curr.next
39+
print() # for a new line
2940

3041

42+
# Creating the linked list 1 -> 2 -> 3 -> 4 -> 5
3143
head = Node(1)
3244
head.next = Node(2)
3345
head.next.next = Node(3)
3446
head.next.next.next = Node(4)
3547
head.next.next.next.next = Node(5)
48+
49+
# Print the original list
50+
print("Original list:")
3651
print_list(head)
52+
53+
# Remove the 5th node from the end (the head in this case)
3754
head = remove(head, 5)
55+
56+
# Print the modified list
57+
print("List after removing the 5th node from the end:")
3858
print_list(head)

0 commit comments

Comments
 (0)