【问题标题】:How do I compare two linked lists in python 3.7?如何比较 python 3.7 中的两个链表?
【发布时间】:2019-01-27 12:55:27
【问题描述】:

首先,我当前的代码:

class linkedlist(object):

    def __init__(self, value, next = None):
        self.value = value
        self.next = next

    def traverse(self):
        field = self
        while field != None:
            print(field.value)
            field = field.next

    def equal(self, other):
        while self and other and self.value== other.value:
            self = self.next
            other = other.next

        if self and other:
            if self.value!= other.value:
                return False
            else:
                return True

我的任务是比较两个链表。如果它们相同,则“equal”函数应返回“True”,如果不是“False”。功能头必须保持这种状态。

我试图自己寻找解决方案 3 小时,但现在我脑残了。谁能给我一些提示/帮助?我不是最好的程序员,所以很抱歉:(

【问题讨论】:

  • self.valueself.nextother 到底是什么?
  • 一旦你比较了self / self.value / other / other.value,你可以使用递归来比较列表的其余部分。
  • 如果其中一个列表较长怎么办?然后,您无法到达 return Truereturn False,因此您返回 None。您是否有一些测试用例要分享,以及它们是如何失败或成功的?
  • @pschill:递归不会让这变得更容易。他们在迭代方法方面做得很好。
  • self = self.next 是通往灾难的道路。引入一个新变量。不要覆盖self。并不是说它不能工作 - 它可以,但代码成为维护的噩梦。

标签: python python-3.x linked-list


【解决方案1】:

你快到了。您正在使用正确的策略来遍历两个链表并跳过任何相等的配对元素(您的第一个循环)。

你出错的地方是你没有处理所有可能的情况之后发生的事情。您现在知道两个链表的前缀介于 0 和 N 个相等的元素之间。您现在可以考虑以下 4 个选项之一:

  1. self 已用尽,但 other 未用尽; other 更长所以不相等,返回 False
  2. other 已用尽,但self 未用尽; self 更长所以不相等,返回 False
  3. selfother 仍然有更多元素,但是两个链表的下一个元素具有不相等的值。返回False
  4. selfother 都用尽了,所以长度相等。它们的前缀是相等的,所以链表是相等的。返回True

您现在只处理选项 3。鉴于 4 个场景中有 3 个导致 return False,因此只测试场景 4 会更容易:

if not self and not other:
    return True
return False

或者,作为一个完整的方法:

def equal(self, other):
    while self and other and self.value == other.value:
        self = self.next
        other = other.next
    if not self and not other:
        return True
    return False

【讨论】:

    猜你喜欢
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2014-12-05
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多