【问题标题】:How to add 2 singly-linked lists together?如何将2个单链表加在一起?
【发布时间】:2019-10-07 22:37:06
【问题描述】:

我正在尝试编写一个将两个链表添加在一起的 Python 函数。每个节点都包含一个可能很大的整数的一位数字,最低有效位在前

Ex 函数: add_linked_list_integers(a, b) - 其中 a 和 b 是单链表,其节点每个都包含一位正整数。

Ex 问题: 617 + 295 = 912 在链表中表示为 (7->1->6) + (5->9->2) = (2-> 1->9)。

我获得了一个基本的ListNode 类,以及用于打印和创建整数链接列表的示例函数。

class ListNode:
    '''Simple node for singly-linked list with _value and _next fields'''
    def __init__(self, value, next=None):
        '''Create a new node, with _value field and optional _next node pointer'''
        self._value = value
        self._next = next

def print_helper(l):
    '''Prints the value of the integer represented by the linked-list l, without trailing carriage return'''
    if l:
        if (l._value < 0) or (l._value > 9):
            raise Exception('digit out of range')
        print_helper(l._next)
        print(l._value, end="")

def print_linked_list_integer(l):
    '''Prints the value of the integer represented by the linked-list l, with trailing carriage return'''
    print_helper(l)
    print()

def create_linked_list_integer(i):
    '''Returns the linked-list representation of the integer i, least-significant digit first'''
    result = ListNode(i % 10)
    if i >= 10:
        result._next = create_linked_list_integer(i // 10)
    return result

def add_linked_list_integers(a, b):
    '''Return the sum of two integers represented as linked lists

目前我的函数如下所示:

def add_linked_list_integers(a, b):
    '''Return the sum of two integers represented as linked lists'''
    answer = ListNode()
    if a == None:
        return b
    elif b == None:
        return a
    carry = 0
    result = (a.data + b.data + carry)
    if result > 9:
        result = result - 10
        carry = 1
        answer.push(result)
    return answer

【问题讨论】:

  • 有什么问题?
  • @MateenUlhaq 我不确定如何添加它们。我怎样才能添加 2 个这样的列表?

标签: python linked-list nodes singly-linked-list


【解决方案1】:
def add_linked_list_integers(a, b):
    '''Return the sum of two integers represented as linked lists'''
    pre_head = ListNode(-1)

    carry = 0
    head = pre_head
    while a is not None and b is not None:
        digit = (a._value + b._value + carry) % 10
        carry = (a._value + b._value + carry) // 10

        head._next = ListNode(digit)
        head = head._next
        a = a._next
        b = b._next

    while a is not None:
        digit = (a._value + carry) % 10
        carry = (a._value + carry) // 10
        head._next = ListNode(digit)
        head = head._next
        a = a._next

    while b is not None:
        digit = (b._value + carry) % 10
        carry = (b._value + carry) // 10
        head._next = ListNode(digit)
        head = head._next
        b = b._next            

    if carry != 0:
        head._next = ListNode(carry)

    return pre_head._next

这就是我要做的

【讨论】:

    【解决方案2】:

    只需执行相当于以 10 为底的加法。这意味着循环数字!

    from itertools import zip_longest
    
    def add_linked_list_integers(xs, ys):
        carry = 0
        result = []
    
        for x, y in zip_longest(xs, ys, fillvalue=0):
            s = x + y + carry
            carry = s // 10
            result.append(s % 10)
    
        if carry > 0:
            result.append(carry)
    
        return result
    

    示例运行:

    >>> add_linked_list_integers([7, 1, 6], [5, 9, 2])
    [2, 1, 9]
    
    >>> to_list = lambda y: [int(x) for x in reversed(str(y))]
    >>> to_int  = lambda xs: int(''.join(str(x) for x in xs)[::-1])
    
    >>> a, b = 3192097619, 999999998472534892
    
    >>> a + b
    1000000001664632511
    
    >>> to_int(add_linked_list_integers(to_list(a), to_list(b)))
    1000000001664632511
    

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 2011-03-15
      • 2011-07-26
      • 1970-01-01
      • 2011-05-21
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多