21.合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-sorted-lists
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
result = ListNode(0)
re = result
while list1 and list2:
num1 = list1.val
num2 = list2.val
if num1 < num2:
re.next = list1
re = re.next
list1 = list1.next
else:
re.next = list2
re = re.next
list2 = list2.next
if list1:
re.next = list1
if list2:
re.next = list2
return result.next