Given the head of a linked list, return the list after sorting it in ascending order.
python 내장 정렬 메서드 사용
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 링크드 리스트의 value만 담을 배열과 current node
arr, curr = [], head
while curr:
arr.append(curr.val)
curr = curr.next
curr = head
for e in sorted(arr):
curr.val = e
curr = curr.next
return head
파이썬 알고리즘 인터뷰 책 참고
class Solution:
def merge(self, l1, l2):
if l1 and l2:
if l1.val > l2.val:
l1, l2 = l2, l1
l1.next = self.merge(l1.next, l2)
return l1 or l2
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
half, slow, fast = None, head, head
while fast and fast.next:
half, slow, fast = slow, slow.next, fast.next.next
half.next = None
l1 = self.sortList(head)
l2 = self.sortList(slow)
return self.merge(l1, l2)