๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿฆ„ | ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต/LeetCode

[LeetCode] 21. Merge Two Sorted Lists (Python)

by KASSID 2023. 4. 10.

๋ชฉ์ฐจ

    728x90

    - Linked List

     

    ๋‚˜์˜ ์ฝ”๋“œ

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
            # empty list
            cNode = result = ListNode()
    
            while list1 and list2:
                if list1.val < list2.val:
                    cNode.next = list1
                    list1, cNode = list1.next, list1
                else :
                    cNode.next = list2
                    list2, cNode = list2.next, list2
                
            if list1 or list2:
                cNode.next = list1 if list1 else list2
    
            return result.next

     

    ์ฝ”๋“œ๋ฆฌ๋ทฐ

    ๋‘ ๊ฐœ์˜ ์ •๋ ฌ๋œ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ•ฉ์ณ์„œ ๋˜ ๋‹ค๋ฅธ ํ•˜๋‚˜์˜ ์ •๋ ฌ๋œ ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

     

    1) ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ ๊ตฌํ˜„

    ๋จผ์ € ํ•ด๋‹น ๋ฌธ์ œ์—์„œ ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ๋Š” ListNode() ํด๋ž˜์Šค๋กœ ๋…ธ๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜์˜€๊ณ 

    ๊ฐ ๋…ธ๋“œ๋Š” ๊ฐ’์„ ์˜๋ฏธํ•˜๋Š” val ๊ณผ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ์˜๋ฏธํ•˜๋Š” next๋ฅผ ๋‹ด๊ณ ์žˆ๋‹ค.

     

    2) ๋‘ ๋ฆฌ์ŠคํŠธ ๋ณ‘ํ•ฉ

     

    โ‘  ๋‘ ๋ฆฌ์ŠคํŠธ์˜ ๋ณ‘ํ•ฉ์„ ๋‹ด์„ ํ•˜๋‚˜์˜ ๊ฒฐ๊ณผ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ(ํ—ค๋“œ ์ƒ์„ฑ)

    cNode = result = ListNode()

    ๊ฒฐ๊ณผ๋ฆฌ์ŠคํŠธ result์— ListNode()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์ดˆ๊ธฐํ™”ํ•˜๊ณ (์ฒซ ๋…ธ๋“œ),

    ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ ๋‚ด์˜ ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ์˜๋ฏธํ•˜๋Š” cNode์— ์ด๋ฅผ ํ• ๋‹นํ•˜์—ฌ ์„œ๋กœ ๊ฐ™์€ ์ฃผ์†Œ๋ฅผ ์ฐธ์กฐํ•˜๋„๋ก ํ•˜์˜€๋‹ค.

     

    โ‘ก ๋‘ ๋ฆฌ์ŠคํŠธ ๋ณ‘ํ•ฉ์„ ์œ„ํ•œ ๋ฐ˜๋ณต๋น„๊ต ๊ณผ์ •

    while list1 and list2:
        if list1.val < list2.val:
            cNode.next = list1
            list1, cNode = list1.next, list1
        else :
            cNode.next = list2
            list2, cNode = list2.next, list2

    list1๊ณผ list2๊ฐ€ ๋ชจ๋‘ None์ด ์•„๋‹Œ ๊ฒฝ์šฐ ๋ฐ˜๋ณต์„ ๊ณ„์† ์ง„ํ–‰ํ•œ๋‹ค.

    ๋งค ๋ฐ˜๋ณต ์„ธ์…˜๋งˆ๋‹ค ๋‘ ๋ฆฌ์ŠคํŠธ์˜ ํ˜„์žฌ ๋…ธ๋“œ ๊ฐ’ ํฌ๊ธฐ๋ฅผ ๋น„๊ตํ•œ๋‹ค.

    ๋” ์ž‘์€ ๊ฒƒ์„ cNode์— ๋‹ด๊ณ , ํ•ด๋‹น ๋…ธ๋“œ์˜ ๋‹ค์Œ์œผ๋กœ ๋„˜์–ด๊ฐ„๋‹ค.

     

    โ‘ข ๋‚จ๋Š” ๋ฆฌ์ŠคํŠธ ์ฒ˜๋ฆฌ

    ๋‘ ๋ฆฌ์ŠคํŠธ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋ชจ๋‘ ๊ฒฐ๊ณผ ๋ฆฌ์ŠคํŠธ์— ๋‹ด๊ธด ๊ฒฝ์šฐ ๋‚˜๋จธ์ง€ ๋ถ€๋ถ„์„ ์ฒ˜๋ฆฌํ•ด์•ผํ•œ๋‹ค.

    if list1 or list2:
        cNode.next = list1 if list1 else list2

    ์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด None์ด ์•„๋‹Œ ๊ฒƒ์„ cNode์˜ ๋‹ค์Œ ๋…ธ๋“œ๋กœ ํ• ๋‹นํ•œ๋‹ค.

     

    โ‘ฃ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜

    ํ˜„์žฌ ์ฒ˜์Œ์— ์„ ์–ธํ•œ result์—๋Š” ๊ฒฐ๊ณผ๋ฆฌ์ŠคํŠธ์˜ ํ—ค๋“œ๋…ธ๋“œ๊ฐ€ ๋‹ด๊ฒจ์žˆ๋‹ค.

    ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ  ํ•จ์ˆ˜๋ฅผ ์ข…๋ฃŒํ•œ๋‹ค.

     

    ๋Œ“๊ธ€