January 9th, 2020
๊ฐ๋จํ Linked list ๋๊ฐ๋ฅผ merge์ํค๋ ๋ฌธ์ ์์. ์ ๋ ๋ list ์ค ํ๋๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ์ ๋ค๋ฅธ list์ node๋ค์ ์ฝ์ ์ํค๋ ๋ฐฉ๋ฒ์ ์๊ฐํ์ด์. Loop ๋ด์์ ์ฐ์ฐ์ ๋ณด๋ค ๊ฐ๋จํ ํ๊ธฐ ์ํด์ ๋ ์์ ๊ฐ์ ๊ฐ๊ณ ์๋ list๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ์์ ํ๊ธฐ๋ก ํ์ด์.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1:
return l2
if not l2:
return l1
head = comp = None
if l1.val <= l2.val:
head, comp = l1, l2
else:
head, comp = l2, l1
gateway = head
while head and comp:
if not head.next:
head.next = comp
return init
if head.next.val < comp.val:
head = head.next
continue
if head.next.val >= comp.val:
tmp = comp
comp = comp.next
tmp.next = head.next
head.next = tmp
head = tmp
return gateway