Skip to content

Commit 5556acb

Browse files
committed
Fix
1 parent 6211693 commit 5556acb

1 file changed

Lines changed: 9 additions & 4 deletions

File tree

data_structures/linked_list/merge_sort_linked_list.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,25 +20,28 @@ def __init__(self, data: int) -> None:
2020
self.next: Node | None = None
2121

2222

23-
def get_middle(head: Node) -> Node:
23+
def get_middle(head: Node | None) -> Node | None:
2424
"""
2525
Find the middle node of the linked list using the slow and fast pointer technique.
2626
2727
Parameters:
2828
head: The head node of the linked list.
2929
3030
Returns:
31-
The middle node of the linked list.
31+
The middle node of the linked list, or None if the list is empty.
3232
3333
Example:
3434
>>> head = Node(1)
3535
>>> head.next = Node(2)
3636
>>> head.next.next = Node(3)
37-
>>> get_middle(head).data
37+
>>> middle = get_middle(head)
38+
>>> middle.data if middle else None
3839
2
40+
>>> get_middle(None) is None
41+
True
3942
"""
4043

41-
if head is None:
44+
if head is None or head.next is None:
4245
return head
4346

4447
slow = head # one node at a time
@@ -153,6 +156,8 @@ def merge_sort_linked_list(head: Node | None) -> Node | None:
153156

154157
# Split the linked list into two halves
155158
middle = get_middle(head)
159+
if middle is None:
160+
return head
156161
next_to_middle = middle.next
157162
middle.next = None # Split the list into two parts
158163

0 commit comments

Comments
 (0)