Linked list sorting (?)
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
import typing
|
||||
|
||||
import stdlib
|
||||
|
||||
|
||||
def yep(s: str) -> bool:
|
||||
return s.strip().lower().startswith("y")
|
||||
@@ -158,3 +160,40 @@ class MinStack:
|
||||
|
||||
def getMin(self) -> int: # no qa
|
||||
return self._min[-1]
|
||||
|
||||
|
||||
def linked_list_to_list(head: stdlib.ListNode | None) -> list[int]:
|
||||
seen: set[int] = set()
|
||||
ret: list[int] = []
|
||||
|
||||
while head is not None:
|
||||
if hash(head) in seen:
|
||||
return ret
|
||||
|
||||
seen.add(hash(head))
|
||||
ret.append(head.val)
|
||||
head = head.next
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
def sort_linked_list(head: stdlib.ListNode | None) -> stdlib.ListNode | None:
|
||||
by_val: list[tuple[int, stdlib.ListNode]] = []
|
||||
ret: stdlib.ListNode | None = None
|
||||
|
||||
while head is not None:
|
||||
by_val.append((head.val, head))
|
||||
head = head.next
|
||||
|
||||
cur = ret
|
||||
|
||||
for _, node in sorted(by_val):
|
||||
if cur is None:
|
||||
cur = ret = stdlib.ListNode(node.val)
|
||||
continue
|
||||
|
||||
next_node = stdlib.ListNode(node.val)
|
||||
cur.next = next_node
|
||||
cur = next_node
|
||||
|
||||
return ret
|
||||
|
||||
Reference in New Issue
Block a user