我只是在尝试我会遇到的一个相当简单的问题,但在编写代码时我似乎遇到了一些困难。以下是代码...功能' my_reverse'是我编码的方式,我似乎无法弄清楚它为什么不起作用(尽管我确定这个错误很简单)。功能'反向'是我在网上找到的一些代码,它确实有效。看来我们的方法非常相似。另外,在while循环中,当你设置nxt = current.nxt,然后设置current.nxt = last,不能使nxt.nxt = last?
class Node:
def __init__(self, val, nxt):
self.val = val
self.nxt = nxt
def my_reverse(n):
if (n.nxt is None):
return n
prev = n
curr = n.nxt
while (curr is not None):
nxt = curr.nxt
curr.nxt = prev
prev = curr
curr = nxt
return prev
def reverse(n):
last = None
current = n
while (current is not None):
nxt = current.nxt
current.nxt = last
last = current
current = nxt
return last
def traverse(n):
iter = n
while iter != None:
print iter.val
iter = iter.nxt
n0 = Node(4, None)
n1 = Node(3, n0)
n2 = Node(2, n1)
n3 = Node(1, n2)
traverse(n3)
l = my_reverse(n3)
traverse(l)
答案 0 :(得分:1)
我认为您的方法很好,除非您忘记终止链接列表。
变化:
prev = n
curr = n.nxt
到
prev = n
curr = n.nxt
n.nxt = None
它有效。