单链表实现两组整数相加(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)

 

posted @ 2018-05-16 16:03  淡季的风  阅读(343)  评论(0编辑  收藏  举报