- ์ฒซ๋ฒ์งธ 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