[LeetCode] Sort List

yoonene·2023년 2월 10일
0

알고리즘

목록 보기
53/62

1트

# 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]:
        if head == []:
            return []
        lst = []
        node = head
        while node is not None:
            lst.append(node.val)
            node = node.next
        
        lst.sort()
        
        # list -> linked list
        answer_lst = ListNode(0)
        result = answer_lst
        for num in lst:
            answer_lst.next = ListNode(num)
            answer_lst = answer_lst.next
        return result.next

  • 연결리스트 알못이라 이번에 ListNode(num)도 처음 알았다.
  • 연결리스트에 값을 넣는 방법을 처음 알았다.
profile
NLP Researcher / Information Retrieval / Search

0개의 댓글