Sorting linked list with mutation (oh no)

This commit is contained in:
Dan Buch 2023-10-21 08:41:41 -04:00
parent 337a795ad0
commit a8d82b180a
Signed by: meatballhat
GPG Key ID: A12F782281063434
2 changed files with 57 additions and 5 deletions

View File

@ -187,13 +187,15 @@ def sort_linked_list(head: stdlib.ListNode | None) -> stdlib.ListNode | None:
cur = ret
for _, node in sorted(by_val):
for _, node in sorted(by_val, key=lambda v: v[0]):
if cur is None:
cur = ret = stdlib.ListNode(node.val)
cur = ret = node
continue
next_node = stdlib.ListNode(node.val)
cur.next = next_node
cur = next_node
cur.next = node
cur = cur.next
if cur is not None:
cur.next = None
return ret

View File

@ -92,6 +92,56 @@ def test_min_stack(ops: list[tuple[str] | tuple[str, int]], expected: list[int |
1, stdlib.ListNode(2, stdlib.ListNode(3, stdlib.ListNode(4)))
),
),
(
stdlib.ListNode(
4,
stdlib.ListNode(
19,
stdlib.ListNode(
14,
stdlib.ListNode(
5,
stdlib.ListNode(
-3,
stdlib.ListNode(
1,
stdlib.ListNode(
8,
stdlib.ListNode(
5, stdlib.ListNode(11, stdlib.ListNode(15))
),
),
),
),
),
),
),
),
stdlib.ListNode(
-3,
stdlib.ListNode(
1,
stdlib.ListNode(
4,
stdlib.ListNode(
5,
stdlib.ListNode(
5,
stdlib.ListNode(
8,
stdlib.ListNode(
11,
stdlib.ListNode(
14, stdlib.ListNode(15, stdlib.ListNode(19))
),
),
),
),
),
),
),
),
),
],
)
def test_sort_linked_list(head: stdlib.ListNode | None, expected: stdlib.ListNode | None):