21. Merge Two Sorted Lists
[Easy] “Merge two sorted linked lists and return it as a new list."
Note: old solution, should review (TODO:
)
Python3:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 and l2:
if l1.val <= l2.val:
l = l1
l1 = l1.next
else:
l = l2
l2 = l2.next
elif l1 and not l2:
return l1
elif l2 and not l1:
return l2
elif (not l1) and (not l2):
return l1
prev = l
while l1 or l2:
if l1 and not l2:
prev.next = l1
return l
elif l2 and not l1:
prev.next = l2
return l
elif l1.val <= l2.val:
prev.next = l1
l1 = l1.next
elif l2.val < l1.val:
prev.next = l2
l2 = l2.next
prev = prev.next
if l1:
prev.next = l1
if l2:
prev.next = l2
return l