티스토리 뷰
https://leetcode.com/problems/sort-list/
Given the head of a linked list, return the list after sorting it in ascending order.
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
문제를 푸는 과정은 간단했다.
연결리스트를 리스트로 구현하고 리스트를 정렬한 후 다시 연결리스트로 구현하는 것이다.
Linked List -> List -> sort -> Linked List
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
p = head
lst = []
while p:
lst.append(p.val)
p = p.next
lst.sort()
p = head
for value in lst:
p.val = value
p = p.next
return head
또 다른 문제의 방법은 Merge Sort를 사용 하는 것이다.