首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将元素的单链表递归和转换为迭代解

如何将元素的单链表递归和转换为迭代解
EN

Stack Overflow用户
提问于 2019-04-26 22:36:20
回答 1查看 93关注 0票数 0

我们有两个单链表;因此,我们只能在一个方向上遍历结构。此外,我们只能访问链表的头部。该算法的目标是将两个链表的数字求和,并产生第三个链表和答案。例如,给定617 + 295 = 912,链表6,1,7+ 2,9,5应该产生结果9,1,2。

为了简单起见,我们将假定原始列表的长度相同。同样,我没有实现链表数据结构;相反,我使用的是Python的内置列表,但将它们视为链表。

我想出的解决方案如下(Python代码)

代码语言:javascript
复制
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的伟大著作“破解编码面试”中发现了最初的问题,它的主题是链表。

EN

回答 1

Stack Overflow用户

发布于 2019-04-26 22:48:03

这里有一个迭代的解决方案:

代码语言:javascript
复制
l1 = [6,1,7]
l2 = [2,9,5]

def iterative_sum(l1, l2):
    maxlength = max(len(l1), len(l2))
    lsum = []
    sup = 0
    for i in range(maxlength):
        if l1 and l2:
            sup, num = divmod(l1.pop() + l2.pop() + sup, 10)
        elif l1 or l2:
            lleft = l1 or l2 # this assigns lleft to one of l1, l2 that still had element
            sup, num = divmod(lleft.pop() + sup, 10)
        lsum.append(num)
    return lsum[::-1]

iterative_sum(l1, l2)
# [9, 1, 2]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55869861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档