将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解题思路
水题,主要用于后面的链表的归并排序做了该题
AC代码
# 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]:res = ListNode()temp = reswhile list1 and list2:if list1.val < list2.val:temp.next = list1temp = temp.nextlist1 = list1.nextelse:temp.next = list2temp = temp.nextlist2 = list2.next temp.next = list1 if list1 else list2return res.next