Nailer's blog

Leetcode merge two sorted lists(Python)

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 

image-20200109144257721

Created by SeongHeum CHOI, 2020