簡體   English   中英

如何將2個單鏈表加在一起?

[英]How to add 2 singly-linked lists together?

我正在嘗試編寫一個 Python function 將兩個鏈表添加在一起。 每個節點包含一個可能較大的 integer 的一位數字,最低有效位在前

例如 Function: add_linked_list_integers(a, b) - 其中 a 和 b 是單鏈表,其節點每個都包含一位正數 integer。

前題: 617 + 295 = 912 在鏈表中表示為 (7->1->6) + (5->9->2) = (2->1->9)。

我提供了一個基本的ListNode class,以及用於打印和創建整數鏈接列表的示例函數。

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

目前我的 function 看起來像這樣:

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

只需執行相當於 base-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
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

這就是我會做的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM