leetcode-top100链表专题二
21.合并两个有序链表
题目链接
21. 合并两个有序链表 - 力扣(LeetCode)
解题代码
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2 # 终止条件,直到两个链表都空
if not l2: return l1
if l1.val <= l2.val: # 递归调用
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
2.两数相加
题目链接
2. 两数相加 - 力扣(LeetCode)
解题思路
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
if not l1: return l2
if not l2: return l1
l1.val += l2.val
if l1.val >= 10:
l1.next = self.addTwoNumbers(ListNode(l1.val // 10),l1.next)
l1.val %= 10
l1.next = self.addTwoNumbers(l1.next,l2.next)
return l1