python如何计算两个单链表所代表的数之和

这篇博客探讨了两种方法来计算由单链表表示的两个数的和。第一种方法是将链表转换为整数并相加,但可能受限于数值范围。第二种方法直接在链表节点上进行相加,同时处理进位问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

“”"
方法一:整数相加法
主要思路:分别遍历两个链表 ,求出两个链表所代表的整数的值,然后把这两个整数进
行相加,最后把它们的和用链表的形式表示出来。这种方法的优点是计算简单,但是有个非
常大的缺点 : 当链表所代表的数很大的时候(超 出 了 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值