one line of code at a time

[leetcode] 21. Merge Two Sorted Lists 파이썬 코드 본문

leetcode

[leetcode] 21. Merge Two Sorted Lists 파이썬 코드

oloc 2024. 8. 11. 04:37

https://leetcode.com/problems/merge-two-sorted-lists/

 

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def mergeTwoLists(self, list1, list2):
        dummy = ListNode()
        tail = dummy # 더미 노드의 마지막을 가리키는 포인터 

        while list1 and list2: # while list1 and list2 are not null
            if list1.val < list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next
        
        # 이 로직이 빠지면 안 됨 
        if list1: # list1 is not null
            tail.next = list1
        else:
            tail.next = list2
        
        return dummy.next

 

참고

https://www.youtube.com/watch?v=XIdigk956u0