作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
<分区>
我们有两个单链表;因此,我们只能在一个方向上遍历结构。此外,我们只能访问链表的头部。该算法的目标是将两个链表的数字相加并产生第三个链表的答案。例如,鉴于 617 + 295 = 912,链表 [6, 1, 7] + [2, 9, 5] 应该产生结果 [9, 1, 2]。
为简单起见,我们假设原始列表的长度相同。同样,我没有实现链表数据结构;相反,我使用 Python 的内置列表,但将它们视为链表。
我想出的解决方案如下(Python代码)
def sum_lists(l1, l2):
lista = []
carry = sum_forward(l1, l2, 0, lista)
if carry > 0:
lista.insert(0, carry)
return lista
def sum_forward(l1, l2, index, lista):
if index == (len(l1)):
return 0
total = l1[index] + l2[index] + sum_forward(l1, l2, index + 1, lista) #here
#we have the iterative call.
carry = total // 10
value = total % 10
lista.insert(0, value) #This way we create a new head for the "surrogate
#linked-list" and append to it the resto of the values
return carry
虽然这个解决方案工作正常,但我听说任何递归解决方案都可以变成迭代解决方案。几天来我一直在努力解决问题,但我无法将其更改为迭代解决方案。
我知道这可以通过多种方式解决;然而,这真的可以变成迭代解决方案吗?
谢谢大家!
我在 Gayle Laakmann Mcdowell 的伟大著作“Cracking the Coding Interview”中找到了链表主题中的原始问题。
我是一名优秀的程序员,十分优秀!