题目详情:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

解答代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
  8. if l1 is None:
  9. return l2
  10. if l2 is None:
  11. return l1
  12. if l1.val <= l2.val:
  13. l1.next = self.mergeTwoLists(l1.next, l2)
  14. return l1
  15. else:
  16. l2.next = self.mergeTwoLists(l1, l2.next)
  17. return l2

解答思路:

最初我并没有想到递归的方法,打算通过创建一个全新的链表,并用while循环遍历两个链表进行比对,返回全新的链表。
在看到这个解法后意识到我的解法太落伍,直接学习了这个思想。