[Leetcode] 21. Merge Two Sorted Lists

서해빈·2021년 3월 9일
0

코딩테스트

목록 보기
9/65

문제 바로가기

Recursion

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def __init__(self):
        self.mergedList = ListNode()
        self.head = self.mergedList

    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not (l1 or l2):
            return self.mergedList.next
        
        if not l1:
            self.head.next = l2
            return self.mergedList.next
        if not l2:
            self.head.next = l1
            return self.mergedList.next
        
        if l1.val < l2.val:
            self.head.next = l1
            l1 = l1.next
        else:
            self.head.next = l2
            l2 = l2.next

        self.head = self.head.next
        return self.mergeTwoLists(l1, l2)

Loop

# 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, l1: ListNode, l2: ListNode) -> ListNode:
        mergedList = ListNode()
        head = mergedList

        while l1 and l2:
            if l1.val <= l2.val:
                head.next = l1
                l1 = l1.next
            else:
                head.next = l2
                l2 = l2.next
            
            head = head.next

        head.next = l1 if l1 else l2

        return mergedList.next

0개의 댓글