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