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

Posted miao-study

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.3如何计算两个单链表代表的数之和相关的知识,希望对你有一定的参考价值。

问题描述

给定两个单链表,链表的每个结点代表一位数,计算两个数的和。例如 :输入链表 (3一>1一> 5)和链表(5一>9一> 2),输出 :8->0->8,即 513+295 =808,注意个位数在链表头。

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

# 输出链表
def print_link(head):
    cur = head.next
    while cur.next != None:
        print(cur.data, end=' ')
        cur = cur.next
    print(cur.data)

# 输出计算结果,将结果链表逆置,从第一的不为0的节点开始输出
def print_str(head):
    cur = head.next
    f = 1
    while cur.next != None:
        if f and cur.data != 0:
            print(cur.data, end='')
            f = 0
        elif f == 0:
            print(cur.data, end='')
        cur = cur.next
    print(cur.data)


# 构造初始链表
def con_link(nums):
    head = Node()
    cur = head
    for num in nums:
        node = Node(num)
        cur.next = node
        cur = node
    return head


# 按位计算,个位->十位->百位以此类推(大整数加法)
def min_compute(p1, p2, p3):
    f = 0
    while p1:
        res = p1.data + p2.data + f
        if res < 10:
            p3.data = res
            f = 0
        else:
            p3.data = res % 10
            f = 1
        p1 = p1.next
        p2 = p2.next
        p3 = p3.next
    while p2:
        res = p2.data + f
        if res < 10:
            p3.data = res
            f = 0
        else:
            p3.data = res % 10
            f = 1
        p2 = p2.next
        p3 = p3.next
    if f == 1:
        p3.data = f

# 逆转链表
def reverse_link(head):
    if head.next == None or head == None:
        return
    pre = head.next
    cur = head.next.next
    pre.next = None
    while cur.next != None:
        next = cur.next
        cur.next = pre
        pre = cur
        cur = next
    cur.next = pre
    head.next = cur
    print_str(head)


def compute(head1, head2, length1, length2):
    p1 = head1.next
    p2 = head2.next
    # 构造结果链表,考虑到进位的情况结果链表长度应该比加数位数多一位
    nums = [0 for i in range(max(length1, length2) + 1)]
    head3 = con_link(nums)
    p3 = head3.next
    # 两个加数长度不同时应该分别考虑
    if length2 >= length1:
        min_compute(p1, p2, p3)
    else:
        min_compute(p2, p1, p3)
    reverse_link(head3)


if __name__ == '__main__':
    s1 = input("link1>>:")
    nums1 = list(map(int, s1.split(' ')))
    length1 = len(nums1)
    s2 = input("link2>>:")
    nums2 = list(map(int, s2.split(' ')))
    length2 = len(nums2)

    link1 = con_link(nums1)
    link2 = con_link(nums2)
    print_link(link1)
    print_link(link2)
    compute(link1, link2, length1, length2)

以上是关于1.3如何计算两个单链表代表的数之和的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript笔试题(js高级代码片段)

单链表学习(五)

算法面试

2.Add Two Numbers

10.两个单链表相交,计算相交点

数据结构单链表