Skip to content

Commit 3d3443a

Browse files
committed
Add doctests for linked list merge sort
1 parent ed7219f commit 3d3443a

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

data_structures/linked_list/merge_sort_linked_list.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,20 @@ def split_middle(node: Node) -> tuple[Node | None, Node | None]:
1414
Returns a tuple containing:
1515
- the node before the middle
1616
- the middle node
17+
18+
>>> head = Node(1)
19+
>>> head.next_node = Node(2)
20+
>>> head.next_node.next_node = Node(3)
21+
>>> head.next_node.next_node.next_node = Node(4)
22+
>>> previous, middle = split_middle(head)
23+
>>> previous is not None
24+
True
25+
>>> middle is not None
26+
True
27+
>>> previous.data
28+
2
29+
>>> middle.data
30+
3
1731
"""
1832
fast = slow = node
1933
previous: Node | None = None
@@ -29,6 +43,30 @@ def split_middle(node: Node) -> tuple[Node | None, Node | None]:
2943
def sort_list(head: Node | None) -> Node | None:
3044
"""
3145
Sort a linked list using merge sort.
46+
47+
>>> head = Node(4)
48+
>>> head.next_node = Node(2)
49+
>>> head.next_node.next_node = Node(1)
50+
>>> head.next_node.next_node.next_node = Node(3)
51+
>>> sorted_head = sort_list(head)
52+
>>> sorted_head is not None
53+
True
54+
>>> sorted_head.data
55+
1
56+
>>> sorted_head.next_node is not None
57+
True
58+
>>> sorted_head.next_node.data
59+
2
60+
>>> sorted_head.next_node.next_node is not None
61+
True
62+
>>> sorted_head.next_node.next_node.data
63+
3
64+
>>> sorted_head.next_node.next_node.next_node is not None
65+
True
66+
>>> sorted_head.next_node.next_node.next_node.data
67+
4
68+
>>> sort_list(None) is None
69+
True
3270
"""
3371
if head is None:
3472
return head
@@ -73,3 +111,33 @@ def sort_list(head: Node | None) -> Node | None:
73111
current = current.next_node
74112

75113
return dummy_head.next_node
114+
115+
116+
def test_merge_sort() -> None:
117+
"""
118+
>>> test_merge_sort()
119+
"""
120+
head = Node(4)
121+
head.next_node = Node(2)
122+
head.next_node.next_node = Node(5)
123+
head.next_node.next_node.next_node = Node(1)
124+
head.next_node.next_node.next_node.next_node = Node(3)
125+
126+
sorted_head = sort_list(head)
127+
128+
assert sorted_head is not None
129+
assert sorted_head.data == 1
130+
assert sorted_head.next_node is not None
131+
assert sorted_head.next_node.data == 2
132+
assert sorted_head.next_node.next_node is not None
133+
assert sorted_head.next_node.next_node.data == 3
134+
assert sorted_head.next_node.next_node.next_node is not None
135+
assert sorted_head.next_node.next_node.next_node.data == 4
136+
assert sorted_head.next_node.next_node.next_node.next_node is not None
137+
assert sorted_head.next_node.next_node.next_node.next_node.data == 5
138+
139+
140+
if __name__ == "__main__":
141+
from doctest import testmod
142+
143+
testmod()

0 commit comments

Comments
 (0)