You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4] Output: [7,0,8] Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0] Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1]
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
题目大意:用两个非空链表来表示两个非负整数,链表的一个节点表示数字的其中一位,数字在链表中是以反顺序存储的,即最低位在前最高位在后。要求相加两个数把和存到一个新链表中。
解题思路:链表题的解法比较单一就是指针的各种操作。这题的两个数相加其实跟我们平时在草稿纸上手算相加两个数是一样的,就是个位与个位相加,大于10就进一位,然后十位与十位相加再与来自个位的进位相加,以此类推直到最高位。由于这题规定的数字最低位在链表的最前面,操作起来就很简单,用两个指针指向两个链表头,相当于两个数的个位是对齐的,用一个循环,两个指针同步向后,逐位相加,相加时要考虑是否有来自低位的进位。要是有一个链表结束而另一链表还没结束,循环继续但只考虑跟进位相加。最后循环结束时判断一下进位值,如果为1,则结果的最高位要增加一个节点。
注:在做链表题时,有一个小技巧会经常用到,就是创建一个新节点指向链表的头节点,这样链表的头节点就相当于一个普通节点而不需要特殊处理。
# 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]:
preHead = ListNode()
cur = preHead
carry = 0
while l1 or l2:
sum = carry
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
cur.next = ListNode(sum % 10)
carry = sum // 10
cur = cur.next
if carry == 1:
cur.next = ListNode(1)
return preHead.next