题目:给定两个单链表,链表的每个结点代表一位数,计算两个数的和。例如:输入链表(3->1->5)和链表(5->9->2),输出8->0->8,即513+295=808.
注意:个位数在链第一个元素。
python3实现该算法,具体如下代码。
#!/usr/bin/python3
class LNode:
"""
链表结点
"""
def __init__(self,x=0):
self.data=x
self.next=None
def genLinkedList(dataList=None):
"""
将List类型转换为链表;
"""
listHead=LNode()
p=listHead
if dataList is not None:
for x in dataList:
nd=LNode(x)
p.next=nd
p=nd
return listHead
def toList(hp):
"""
将链表转换为List
"""
if hp is None or hp.next is None:
return []
lst=[]
p=hp.next
while p is not None:
lst.append(p.data)
p=p.next
return lst
def add(h1,h2):
"""
计算单链表之和;
c表示进位。
"""
if h1 is None or h1.next is None:
return h2
if h2 is None or h2.next is None:
return h1
p1=h1.next
p2=h2.next
tmp=None
c=0
resultHead=LNode()
p=resultHead
while p1 is not None and p2 is not None:
tmp=LNode()
sums=p1.data+p2.data+c
tmp.data=sums%10
#c=round(sums/10)
c=1 if sums >=10 else 0
p.next=tmp
p=tmp
p1=p1.next
p2=p2.next
px=p1 if p2 is None else p2
while px is not None:
tmp=LNode()
sums=px.data+c
tmp.data=sums%10
c=1 if sums >=10 else 0
p.next=tmp
p=tmp
px=px.next
if c==1:
tmp=LNode(c)
p.next=tmp
p=tmp
return resultHead
if __name__=='__main__':
list1=[3,4,5,6,7,8]
list2=[9,8,7,6,5]
hp1=genLinkedList(list1)
hp2=genLinkedList(list2)
print('List 1st:{L1}'.format(L1=list1))
print('List 1st:{L2}'.format(L2=list2))
res=add(hp1,hp2)
print('List Ret:{LRes}'.format(LRes=toList(res)))