【题目】:
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.【题意】:
给定两个非空的链表来表示两个非负的整数,链表中的数字是逆向存储的,如2 -> 4 ->3表示的是342。
【参考】:参考资料
【思路】:用两个指针指向两个链表的头(数字的最低位),分别进行相加,并判断是否超过10;若超过10,则下一次的相加需要加1。还需要注意的情况是1. 两个链表不等长 2.两个链表中有一个链表为空 3. 9+1 =10,需要额外增加节点的情况
【Python代码】:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
flag = 0
dummy_node = ListNode(0)
current = dummy_node
while l1 or l2:
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
sum = l1_val + l2_val + flag
current.next = ListNode(sum % 10)
current = current.next
flag = sum // 10
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if flag > 0:
current.next = ListNode(1)
return dummy_node.next
本文介绍了一种使用链表表示非负整数并实现两数相加的方法。通过遍历两个链表,逐位相加并处理进位,最终返回新的链表结果。
1272

被折叠的 条评论
为什么被折叠?



