【发布时间】:2021-03-14 06:05:02
【问题描述】:
节点和链表类:
class Node:
def __init__(self, elm, nxt):
self.elm = elm
self.nxt = nxt
class LnLs:
def __init__(self, s = None):
self.head = None
if s:
for x in s:
self.push(x)
self.reverse()
def __bool__(self):
return self.head is not None
def top(self):
if not self:
raise IndexError
return self.head.elm
def push(self, x):
self.head = Node(x, self.head)
def pop(self):
x = self.top()
self.head = self.head.nxt
return x
def __iter__(self):
p = self.head
while p:
yield p.elm
p = p.nxt
def index_of(self, x):
for i, y in enumerate(self):
if x == y:
return i
return -1
def __getitem__(self, i):
for j, x in enumerate(self):
if i == j:
return x
raise IndexError
def reverse(self):
q, p = None, self.head
# q points to the previous node
while p:
t = p.nxt
p.nxt = q
q = p
p = t
self.head = q
def reverse(h, q):
if h.head is None:
return q
else:
t = h.head.nxt
h.head.nxt = q
return reverse(t, h)
无论我做什么,我都无法让它工作我尝试在 Node 类中添加另一个 reverse(h,q)。 我已经尝试了至少 5 个小时,任何帮助将不胜感激! 这实际上是我的任务,我有去年完全相同的问题的答案,即
def reverse(h, q):
if h is None:
return q
else:
t = h.nxt
h.nxt = q
return reverse(t, h)
EDIT1:对于糟糕的提问技巧感到抱歉。这是我第一次在这里提问。我正在尝试使用此函数使用另一个空链表 q 反转链表 h。例如我的链表是:1->2->3。如果我输入:“ll.reverse(LnLs())”,那么我希望我的链接将更改为 3->2->1。起初我运行这段代码,它说“AttributeError:'LnLs'对象没有属性'nxt'”。然后我把代码改成:
def reverse(h, q):
if h.head is None:
return q
else:
t = h.head.nxt
h.head.nxt = q
return reverse(t, h)
现在它显示 NameError: name 'reverse' is not defined。如果我以另一种缩进的形式添加这个函数(对不起,我不知道这在Python中叫什么,我以一张图片为例):
然后我运行测试代码,现在我的链接只有一个元素:
if __name__ == '__main__':
ll = LnLs()
ll.push('apple')
ll.push('orange')
ll.push('peach')
for x in ll:
print(x)
ll.reverse(LnLs())
for x in ll:
print(x)
输出: 桃子 橙 苹果 桃子
这是我感到困惑的地方,因为我不知道我还能做什么。再次感谢。
【问题讨论】:
-
请提供预期的MRE - Minimal, Reproducible Example。显示中间结果与预期结果的偏差。我们应该能够将您的代码块粘贴到文件中,运行它并重现您的问题。这也让我们可以在您的上下文中测试任何建议。您发布的代码没有做任何事情:您有两个类和一个函数,但这些都没有被调用过。
-
我们还希望您在错误点之前跟踪可疑值。您对他们如何获得这些价值观感到困惑? “不能让它工作”不是问题规范。
标签: python linked-list singly-linked-list