【问题标题】:Linked list iteration running infinitely链表迭代无限运行
【发布时间】:2021-04-07 07:06:26
【问题描述】:

我实现了一个链表。现在我应该对两个链表的每个对应项求和。

这是链表的实现

class Node:
    def __init__(self, data=0, next_node=None):
        self.data = data
        self.next_node = next_node


class LinkedList:
    def __init__(self):
        self.head = None

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current.data
            current = current.next_node
    
    def add_last(self, node):
        if self.head is None:
            self.head = node
            return

        current = self.head

        while current.next_node:
            current = current.next_node

        current.next_node = node

但是当我对每个链表的项目求和时,我有一个无限循环并且我的链表没有迭代

这是求和过程


def two_sum(list1: LinkedList, list2: LinkedList) -> LinkedList:
    l1 = list1.head
    l2 = list2.head
    res_list = LinkedList()
    carry = 0

    while l1 is not None or l2 is not None:
        x = l1.data if l1 else 0
        y = l2.data if l2 else 0

        sum = carry + x + y

        res_list.add_last(Node(sum % 10))

        carry = carry // 10

        l1 = l1.next_node if l1.next_node else l1
        l2 = l2.next_node if l2.next_node else l2

    if carry > 0:
        res_list.add_last(Node(carry))
    
    return res_list

【问题讨论】:

  • 你不会从下一个节点前进,所以你永远不会到达最后的Nonewhile 循环中的最后两行应该是 lx = lx.next_node if lx else lx 或者可能是 if lx: lx = lx.next_node

标签: python algorithm linked-list


【解决方案1】:

注意:

l1 = l1.next_node if l1.next_node else l1
l2 = l2.next_node if l2.next_node else l2

错了。

那个条件:

if l1.next_node

不会将 None 分配给 l1/l2

你可以放弃if l1.next_node else l1

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2015-01-04
    • 1970-01-01
    相关资源
    最近更新 更多