问题1 描述
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
分析:
创建一个新的链表来记录每次的和,使用哑节点表示新链表的头。
需要考虑的问题
1:
两个链表长度不一样,比如
3->10->null
5->11->9->null
和是8->1->1->1->null
2:
进位的处理用到%和//
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
def addlist(l1,l2):
dummy=ListNode(0)
current=dummy
flag=0
while l1 or l2:
if l1:
x=l1.val
l1=l1.next
else:
x=0
if l2:
y=l2.val
l2=l2.next
else:
y=0
sum=x+y+flag
current.next=ListNode(sum%10)
flag=sum//10
current=current.next
if flag==1: #最后一个节点是否需要进位
current=current.next
return dummy.next
else:
return dummy.next
问题2 描述
假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例
给出 6->1->7 + 2->9->5。即,617 + 295。
返回 9->1->2。即,912 。
分析:
上一题是从左往右进位,这里是右往左进位。
最直观的方法是翻转链表,然后按照上一题中的方法求解。
关于翻转链表,我的另一篇文章有具体实现和解释
def reverse(head):
p=head
q=head.next
head.next=None
while q:
r=q.next
q.next=p
p=q
q=r
newhead=p
return newhead
def addLinkedlist2(l1,l2):
newl1=reverse(l1)
newl2=reverse(l2)
dummy=ListNode(0)
current=dummy
flag=0
while newl1 or newl2:
if newl1:
x=newl1.val
newl1=newl1.next
else:
x=0
if newl2:
y=newl2.val
newl2=newl2.next
else:
y=0
sum=x+y+flag
current.next=ListNode(sum%10)
flag=sum//10
current=current.next
if flag:
current.next=ListNode(flag)
return reverse(dummy.next)
else:
return reverse(dummy.next)