From a8d82b180a48ea9f8d4c2336be21dbf6167a6ec8 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 21 Oct 2023 08:41:41 -0400 Subject: [PATCH] Sorting linked list with mutation (oh no) --- leetcode/stuff.py | 12 +++++----- leetcode/test_stuff.py | 50 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/leetcode/stuff.py b/leetcode/stuff.py index 6c1f3ea..29096a4 100644 --- a/leetcode/stuff.py +++ b/leetcode/stuff.py @@ -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 diff --git a/leetcode/test_stuff.py b/leetcode/test_stuff.py index bf26267..941392b 100644 --- a/leetcode/test_stuff.py +++ b/leetcode/test_stuff.py @@ -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):