Published:
Updated:

  • ์ฒซ๋ฒˆ์งธ for๋ฌธ์ด ์ดํ•ด๊ฐ€ ๋˜์งˆ ์•Š๋Š”๋‹ค๋ฉด ์ด์ฝ”ํ…Œ ์ •๋ ฌ ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ์˜ค๋Š” ๊ฑธ ๊ถŒ์žฅํ•จ


Solution

# Definition for singly-linked list.
from typing import Optional


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        # linked๋ฅผ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
        linked_to = []
        cur = head
        while cur:
            linked_to.append(cur.val)
            cur = cur.next

        for i in range(1, len(linked_to)):
            # i๋ถ€ํ„ฐ 1๊นŒ์ง€ -1(๊ฐ์†Œ)์”ฉ ๋ฐ˜๋ณต
            for j in range(i, 0, -1):
                # ์™ผ์ชฝ์ด ์˜ค๋ฅธ์ชฝ๋ณด๋‹ค ๋” ํด ๊ฒฝ์šฐ, ํ•œ ์นธ์”ฉ ์™ผ์ชฝ์œผ๋กœ ์ด๋™
                if linked_to[j] < linked_to[j - 1]:
                    linked_to[j], linked_to[j - 1] = linked_to[j - 1], linked_to[j],
                    continue

                break

        # ์ •๋ ฌ์ด ์™„๋ฃŒ๋์œผ๋‹ˆ ๋ฐฐ์—ด์„ ๋‹ค์‹œ linked๋กœ ๋ณ€ํ™˜
        # ์ƒˆ๋กœ์šด linked์˜ head ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑ -> ์ฒซ ๋ฒˆ์งธ ์›์†Œ ๊ธฐ์ค€
        new_head = ListNode(linked_to[0])
        cur = new_head

        # ์ฒซ๋ฒˆ์งธ(0)๋Š” new_head๋กœ ์ด๋ฏธ ์†Œ๋น„๋˜์—ˆ์œผ๋ฏ€๋กœ ๋‘๋ฒˆ์งธ(1)๋ถ€ํ„ฐ
        for val in linked_to[1:]:
            # ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑ ํ›„ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ํ•จ
            cur.next = ListNode(val)
            cur = cur.next

        return new_head


Reference

Leave a comment