Chapter 2 Linked Lists - 2.4

Problem 2.4: You have two numbers represented by a linked list, where each node contains a single digit. The digit are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3->1->5)+(5->9->2)
Output: 8->0->8


The first solution came into my mind is quite "Engineering". I divided the problem into sub-problems( list_to_num and num_to_list) and let the adder do the computation.
class node:
    def __init__(self, data=None):
        self.data = data
        self.next = None

def add_two_lists(l1, l2):
    num1 = list_to_num(l1)
    num2 = list_to_num(l2)
    sum = num1 + num2
    return num_to_list(sum)

def list_to_num(l):
    sum = 0
    i = 0
    while l != None:
        sum = sum + l.data*(10**i)
        i = i + 1
        l = l.next
    return sum

def num_to_list(num):
    # First node is a dummy node
    # for simplifying the operation
    head = n = node()
    i = 1
    while num != 0:
        current_digit = (num%(10**i))/(10**(i-1))
        n.next = node(current_digit)
        n = n.next
        num = num - current_digit*(10**(i-1))
        i = i + 1
    to_return = head.next
    del head
    return to_return

if __name__ == "__main__":
    # The first list
    n11 = node(5)
    n12 = node(1)
    n13 = node(4)
    n11.next = n12
    n12.next = n13
    # The second list
    n21 = node(3)
    n22 = node(3)
    n23 = node(6)
    n21.next = n22
    n22.next = n23
    # Add the two lists
    l = add_two_lists(n11, n21)
    while l != None:
        print l.data,
        l = l.next
    print "\n"
A more direct one is:
def add_two_lists(l1, l2):
    # Add a dummy node for convenience
    head = n = node()
    carry = 0
    while (l1 != None) or (l2 != None):
        num1 = num2 = 0
        if l1 != None:
            num1 = l1.data
        if l2 != None:
            num2 = l2.data
        sum = num1 + num2 + carry
        carry = int(sum/10)
        n.next = node(sum%10)
        n = n.next
        l1 = l1.next
        l2 = l2.next
    if carry != 0:
        n.next = node(carry)
    to_return = head.next
    del head
    return to_return
At first, I forgot to increase the loop variants again... How many times?!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值