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

本文介绍了一种使用链表表示数字并进行加法运算的方法,包括带头结点和不带头结点两种实现方式,详细解释了算法流程及性能分析。

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

 题目描述:

给定两个单向链表,链表的每个节点代表一位数,计算两个数的和

方法分析:

方法一: 整数相加

分别遍历两个链表所代表的值,然后将两个整数加到一起

方法二:链表相加法

对链表中的节点直接进行相加操作,把相加的和存储到新的链表中对应的节点中,同时还要记录节点相加后的进位。

算法性能分析:

这种方法需要对两个链表遍历,因此时间复杂度为o(N),由于计算结果保存在一个新的链表中,空间复杂度为o(N)

代码实现:

1. 带头节点实现

带头结点实现
class LNode:
    def __init__(self, item):
        self.data = item
        self.next = None


def add(h1, 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
    sum = 0
    p1 = h1.next
    p2 = h2.next
    tmp = None
    result_head = LNode(None)
    result_head.next = None
    p = result_head

    while p1 is not None and p2 is not None:
        sum = p1.data + p2.data + c
        tmp = LNode(sum % 10)
        tmp.next = None
        c = sum // 10
        p.next = tmp
        p = tmp
        p1 = p1.next
        p2 = p2.next

    if p1 is None:
        while p2 is not None:
            sum = p2.data + c
            tmp = LNode()
            tmp.next = None
            tmp.data = sum % 10
            c = sum // 10
            p.next = tmp
            p = tmp
            p2 = p2.next
    if p2 is None:
        while p1 is not None:
            sum = p1.data + c
            tmp = LNode(sum % 10)
            tmp.next = None
            c = sum // 10
            p.next = tmp
            p1 = p1.next
    if c == 1:
        tmp = LNode(1)
        tmp.next = None
        p.next = tmp
    return result_head

if __name__ == '__main__':
    i = 1
    head1 = LNode(None)
    head1.next = None
    head2 = LNode(None)
    head2.next = None
    tmp = None
    cur = head1
    add_result = None

    while i < 7:
        tmp = LNode(i+2)
        tmp.next = None
        cur.next = tmp
        cur = tmp
        i += 1
    print("i的值为:%d"%i)

    i = 9
    cur = head2
    while i > 4:
        tmp = LNode(i)
        tmp.next = None
        cur.next = tmp
        cur = tmp
        i -= 1


    print("\nhead1")
    cur = head1.next
    while cur is not None:
        print(cur.data)
        cur = cur.next

    print("\nhead2")
    cur = head2.next
    while cur is not None:
        print(cur.data)
        cur = cur.next

    add_result = add(head1, head2)
    print("\n相加后:")
    cur = add_result.next
    while cur is not None:
        print(cur.data)
        cur = cur.next

代码运行结果:

head1
3
4
5
6
7
8

head2
9
8
7
6
5

相加后:
2
3
3
3
3
9

2. 不带头结点

class LNode:
    def __init__(self, item):
        self.data = item
        self.next = None

def add(h1, h2):
    if h1 is None:
        return h2
    if h2 is None:
        return h1
    c = 0
    sum = 0
    p1 = h1
    p2 = h2
    tmp = None
    result_head = None
    p = result_head
    while p1 is not None and p2 is not None:
        sum = p1.data + p2.data + c
        tmp = LNode(sum % 10)
        tmp.next = None
        c = sum // 10
        if p is not None:
            p.next = tmp
            p = tmp
        else:
            result_head = tmp
            p = result_head
        p1 = p1.next
        p2 = p2.next

    if p1 is None:
        while p2 is not None:
            sum = p2.data + c
            tmp = LNode()
            tmp.next = None
            tmp.data = sum % 10
            c = sum // 10
            p.next = tmp
            p = tmp
            p2 = p2.next
    if p2 is None:
        while p1 is not None:
            sum = p1.data + c
            tmp = LNode(sum % 10)
            tmp.next = None
            c = sum // 10
            p.next = tmp
            p1 = p1.next
    if c == 1:
        tmp = LNode(1)
        tmp.next = None
        p.next = tmp
    return result_head

if __name__ == '__main__':
    i = 1
    head1 = None
    head2 = None
    tmp = None
    cur = head1
    add_result = None

    while i < 7:
        tmp = LNode(i+2)
        tmp.next = None
        if cur is not None:
            cur.next = tmp
            cur = tmp
        else:
            head1 = tmp
            cur = head1
        i += 1
    print("i的值为:%d"%i)

    i = 9
    cur = head2
    while i > 4:
        tmp = LNode(i)
        tmp.next = None
        if cur is not None:
            cur.next = tmp
            cur = tmp
        else:
            head2 = tmp
            cur = head2
        i -= 1

    print("\nhead1")

    cur = head1
    while cur is not None:
        print(cur.data)
        cur = cur.next

    print("\nhead2")
    cur = head2
    while cur is not None:
        print(cur.data)
        cur = cur.next

    add_result = add(head1, head2)
    print("\n相加后:")
    cur = add_result
    while cur is not None:
        print(cur.data)
        cur = cur.next

 

### 合并两个有序单链表为降序链表 要将两个已按升序排列的单链表合并成一个按降序排列的新链表,可以采用逆向思维的方式处理。以下是具体方法: #### 方法概述 通过遍历两个输入链表中的节点,比较当前节点值大小,并按照从大到小顺序构建新链表。由于题目要求不额外分配存储空间,因此可以直接修改原链表指针来完成操作。 #### 实现细节 1. 创建一个虚拟头结点 `dummy` 和指向该节点的工作指针 `current`。 2. 遍历两个链表直到其中一个为空为止,在每次迭代过程中选取较大值作为下一个节点加入结果链表中。 3. 如果某个链表已经全部被处理完毕,则把另一个剩余部分直接连接至结果链表后面即可。 4. 反转最终得到的结果链表使其成为降序形式[^1]。 下面是基于上述逻辑编写的 Python实现: ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(-1) current = dummy while l1 and l2: if l1.val >= l2.val: current.next = l1 l1 = l1.next else: current.next = l2 l2 = l2.next current = current.next # 连接剩下的元素 current.next = l1 or l2 head = reverseList(dummy.next) return head def reverseList(head: ListNode) -> ListNode: prev = None curr = head while curr is not None: temp_next = curr.next curr.next = prev prev = curr curr = temp_next return prev ``` 此代码定义了一个辅助类 `ListNode` 来表示单链表节点以及函 `mergeTwoLists()` 完成了主要功能——即接收两棵二叉树根节点参并将它们组合起来形成新的降序列表;还提供了反转链表所需的工具函 `reverseList()`.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值