티스토리 뷰

카테고리 없음

sort - sort-list

날따라해봐요요롷게 2022. 1. 31. 14:49

https://leetcode.com/problems/sort-list/

 

Sort List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

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를 사용 하는 것이다.

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함