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.
逐个遍历两个链表的每个节点,并计算对应节点位置的和。主要需要考虑一个进位的问题,用carry来储存每轮计算后的进位值。
因为需要返回的是整个新列表,所以定义了两个变量。返回的链表指针始终在初始位置,而复制变量的指针循环结束后在链表末尾。
# 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
"""
# 进位
carry = 0
# 定义变量用来保存sum结果
result = ListNode(0)
n = result
# result = n = ListNode(0)
# 遍历链表
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
# 取得新链表的节点,进位带入一个循环
val = carry%10
carry = carry//10
n.next = ListNode(val)
n = n.next
#n.next = n = ListNode(val)
# result第一个值为0,返回result.next
return result.next
这个solution是参考论坛的方法,这里最开始有个疑问,就是将一个变量赋值给另一个变量的时候,或者说复制一个变量,改变其中一个变量的值会不会影响另一个变量?下面链接有python详细的解释。
在这里简单总结一下,如果被复制变量是可变型的(如列表或字典)且不使用切片复制,那么改变其中一个变量中某个元素的值,会同时改变两个变量。其它情况,比如,被复制变量是整数或字符,或者对其中一个变量整个重新赋值,则不会影响另一个变量。
>>>a = ['blue','green']
>>>b = a
>>>print(a)
>>>print(b)
['blue','green']
['blue','green']
>>>b[0] = ['red']
>>>print(a)
>>>print(b)
['red','green']
['red','green']
>>>b = ['black,'white']
>>>print(a)
>>>print(b)
['red','green']
['black,'white']
参考资料:
https://www.python-course.eu/deep_copy.php
https://leetcode.com/problems/add-two-numbers/discuss/1016/Clear-python-code-straight-forward?page=4