题目详情:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
解答代码
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:if l1 is None:return l2if l2 is None:return l1if l1.val <= l2.val:l1.next = self.mergeTwoLists(l1.next, l2)return l1else:l2.next = self.mergeTwoLists(l1, l2.next)return l2
解答思路:
最初我并没有想到递归的方法,打算通过创建一个全新的链表,并用while循环遍历两个链表进行比对,返回全新的链表。
在看到这个解法后意识到我的解法太落伍,直接学习了这个思想。
