subject :
Merge two ascending linked lists into a new Ascending Link list and return . The new linked list is made up of all the nodes of the given two linked lists .
Example 1:
Input :l1 = [1,2,4], l2 = [1,3,4]
Output :[1,1,2,3,4,4]
Example 2:
Input :l1 = [], l2 = []
Output :[]
Example 3:
Input :l1 = [], l2 = [0]
Output :[0]
code:
# 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]:
if not list1 :
return list2
elif not list2:
return list1
res = ListNode()
ans = res
while list1 != None and list2 != None:
if list1.val <= list2.val:
ans.next = list1
list1 = list1.next
else:
ans.next = list2
list2 = list2.next
ans = ans.next
if list1 == None:
ans.next = list2
else:
ans.next = list1
return res.next