2. 两数相加
题目地址: https://leetcode-cn.com/problems/add-two-numbers/submissions/
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
Python 里面没有链表这种类型,所以只能自定义。
解题思路:
从第一个数字开始往下走,直到最后一个。没有什么特别的思路
代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
t_l1=l1
t_l2=l2
result=ListNode(0)
current_node = result
while t_l1 != None or t_l2 != None:
if t_l1!=None:
current_node.val=current_node.val+t_l1.val
if t_l2!=None:
current_node.val=current_node.val+t_l2.val
print(current_node.val)
if current_node.val>=10:
new_node = ListNode(1)
current_node.val = current_node.val - 10
else:
new_node = ListNode(0)
if t_l1 !=None:
t_l1 = t_l1.next
if t_l2 !=None:
t_l2 = t_l2.next
if t_l1 == None and t_l2 == None and new_node.val == 0:
break
current_node.next=new_node
current_node=new_node
return result
没想到速度这么快:
 {
var next: ListNode = null
var x: Int = _x
}
object Solution {
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
var result:ListNode=null
var current:ListNode=null
var t_l1=l1
var t_l2=l2
var z=0
while (t_l1 != null || t_l2 != null){
var x=if (t_l1 == null) 0 else t_l1.x
var y=if (t_l2 == null) 0 else t_l2.x
println(x+":"+y)
var new_node = new ListNode()
if ( x + y + z >= 10 ){
new_node=new ListNode(x+y+z-10)
z=1
}else{
new_node=new ListNode(x+y+z)
z=0
}
println("1")
if (current == null ){
result=new_node
current=new_node
}else{
current.next=new_node
current=new_node
}
println("2")
t_l1=if (t_l1 == null ) null else t_l1.next
t_l2=if (t_l2 == null ) null else t_l2.next
println("3")
}
if (z==1){
current.next=new ListNode(1)
}
return result
}
}
遇到的小要点
- 判断变量是否为None的时候,不需要再写 !=None了,直接写如下的代码:
while(l1 or l2):
...
x= l1.val if l1 else 0
- Scala里面
如果定义
var a=null
后面再赋值 a=new ListNode(0) 会报错,类型不匹配
可以定义
var a:ListNode=null
后面再赋值就不会报错了!