单链表实现两组整数相加(python)

比如

1->2->4->6->7 + 3->4->5   =>  1->2->8->1>2

思想是先把两个链表反转, 从低位相加, 得到结果, 再反转回来#! /usr/bin/env python# -*- coding: utf-8 -*-


class Node(object):

    def __init__(self, data, next):
        if data not in range(10):
            raise ValueError
        self.data = data
        self.next = next


def reverse(head):
    if head is None or head.next is None:
        return head

    pre = None
    current = head
    while current:
        tmp = current
        current = current.next
        tmp.next = pre
        pre = tmp

    return pre


def print_node(head):
    result = ""
    while head:
        result += str(head.data) + "->"
        head = head.next
    print result


def add(node1, node2):
    x = reverse(node1)
    y = reverse(node2)

    i = 0
    pre = None
    while x or y:
        tmp = i

        if x:
            tmp += x.data
            x = x.next

        if y:
            tmp += y.data
            y = y.next

        if tmp >= 10:
            tmp -= 10
            i = 1
        else:
            i = 0
        t = Node(tmp, None)
        t.next = pre
        pre = t
if i>0:
t = Node(i, None)
t.next = pre
return t if __name__ == "__main__": h = Node(1, Node(2, Node(4, Node(6, Node(8, None))))) h1 = Node(3, Node(4, Node(5, None))) print_node(h) print_node(h1) r = add(h, h1) print_node(r)

 

转载于:https://www.cnblogs.com/lowseasonwind/p/9046493.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值