“”"
方法一:整数相加法
主要思路:分别遍历两个链表 ,求出两个链表所代表的整数的值,然后把这两个整数进
行相加,最后把它们的和用链表的形式表示出来。这种方法的优点是计算简单,但是有个非
常大的缺点 : 当链表所代表的数很大的时候(超 出 了 long 的表示范围〉,就无法使用这种方
法了。
“”"
“”"
主要思路 : 对链表中的结点直接进行相加操作,把相加的和存储到新的链表中对应的结
点中,同时还要记录结点相加后的进位。
“”"
class LNode:
def _new_(self, x):
self.data = x
self.next = None
def add(h1, h2):
"""
方法功能:对两个带头结点的单链表所代表的数相加
输入参数: hl :第一个链表头结点: h2:第二个链表头结点
返回值 : 相加后链表的头结点
"""
if h1 is None or h1 .next is None:
return h2
if h2 is None or h2.next is None:
return h1
c = 0
sums = 0
p1 = h1.next
p2 = h2.next
tmp = None
resultHead = LNode()
resultHead.next = None
p=resultHead
while p1 is not None and p2 is not None:
tmp = LNode()
tmp.next = None
sums = p1.data+p2.data+c
tmp.data = sums % 10
c = sums//10
p.next = tmp
p = tmp
p1 = p1.next
p2 = p2.next
# 链表 h2 比 hl 长,接下来只需要考虑 h2 剩余结点的值
if p1 is None:
while p2 is not None:
tmp=LNode()
tmp.next=None
sums=p2.data+c
tmp.data=sums % 10
c=sums//10
p.next=tmp
p=tmp
p2=p2.next
# 链表 hi 比 h2 长,接下来只需要考虑 hl 剩余结点的值
if p2 is None:
while p1 is not None:
tmp=LNode()
tmp.next=None
sums=p1.data+c
tmp.data=sums% 10
c=sums/10
p.next=tmp
p=tmp
p1=p1.next
# 如果计算完成后还有进位,则增加新的结点
if c==1:
tmp=LNode()
tmp.next=None
tmp.data=1
p.next=tmp
return resultHead
if __name__ =="__main__":
list1 = [3,1,5]
list2 = [5,9,2]
head1=LNode()
head1.next=None
head2=LNode()
head2.next=None
tmp=None
cur=head1
addResult=None
# 构造第一个链表
for i in list1:
tmp=LNode()
tmp.data=i
tmp.next=None
cur.next=tmp
cur=tmp
cur=head2
# 构造第二个链表
for i in list2:
tmp=LNode()
tmp.data=i
tmp.next=None
cur.next=tmp
cur=tmp
print("\nHeadl :")
cur=head1.next
while cur is not None:
print(cur.data,end=" ")
cur=cur.next
print("\nHead2 :")
cur=head2.next
while cur is not None:
print(cur.data,end=" ")
cur=cur.next
addResult=add(head1,head2)
print("\n相加后")
cur=addResult.next
while cur is not None:
print(cur.data,end=" ")
cur=cur.next