기록하는 공간

[leetcode/python3] 21. Merge Two Sorted Lists 본문

알고리즘/leetcode

[leetcode/python3] 21. Merge Two Sorted Lists

llollhh_ 2023. 2. 8. 19:40

 

 

Merge Two Sorted Lists - LeetCode

Merge Two Sorted Lists - You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.

leetcode.com

 

# 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]:
        dummy = ListNode()
        head = dummy

        while list1 != None and list2 != None:
            if list1.val < list2.val:
                head.next = list1
                list1 = list1.next
            else: 
                head.next = list2
                list2 = list2.next

            head = head.next

        head.next = list1 or list2

        return dummy.next

자료구조는 Linked List를 사용

Comments