見出し画像

21. Merge Two Sorted Lists

# 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, l2):
       # input: l1: ListNode
       #        l2: ListNode
       # output: ListNode:
       if not l1 or not l2:
           return l1 or l2
       head = cur = ListNode(0)
       while l1 and l2:
           if l1.val < l2.val:
               cur.next = l1
               l1 = l1.next
           else:
               cur.next  = l2
               l2 = l2.next
           cur = cur.next

       cur.next = l1 or l2
       return head.next




いいなと思ったら応援しよう!