单链表实现两组整数相加

比如

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

    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)

猜你喜欢

转载自www.cnblogs.com/lowseasonwind/p/9046493.html