【发布时间】: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