我只是在尝试,尽管那将是一个相当简单的问题,但是在编写代码时,我似乎遇到了一些困难。下面是代码...函数'my_reverse'是我编写代码的方式,我似乎无法弄清为什么它不起作用(尽管我确定错误很简单)。函数“ 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)
最佳答案
我认为您的方法不错,只是您忘记了终止链表。
更改:
prev = n
curr = n.nxt
至
prev = n
curr = n.nxt
n.nxt = None
而且有效。