更新我自己,以及对挑战的修订:
该算法确实有效,它只是以一种令人困惑的方式编写并且不包括第一个节点(它仅用于副作用),这本身就是一个......有问题的设计。
重写它以避免无用d.next
和t
更好的范围,使其更容易(并且对我来说可能)遵循:
public void reverse(Node<T> h) { // draw H under first node
Node<T> d = null
while (h.next != null) {
Node<T> t = h.next; // draw T under box at end of H arrow (remove any previous T)
h.next = t.next; // change arrow from H to end where arrow from box above T ends (no arrow for last element)
t.next = d; // draw arrow from box above T to box D is under (no arrow for first element)
d = t; // draw D under box (remove any previous D)
}
h.next = d; // draw arrow from H to box D is under
}
上箱子!
(我建议查看Reverse a Linked-List中的代码,它是相同的概念,但更容易理解并且没有此实现的假头节点。)
我知道我说过“只画盒子”。所以,在你的更多评论之后,我画了盒子。(我假装我回到了大学;-)
但是,我也无法让它工作。我什至尝试过圈子。
我怀疑发布的代码不是一个有效的实现(现在其他人现在证明我错了这是一个公开的挑战;至少它可以让这个问题保持开放;-)
I have not been able to use it to reverse a list of 2, 3 or 4 elements in length after several attempts (although I have been able to successfully use the [much more intuitive] code presented in Reverse a Linked-List).
I believe there is a flaw in using h.next
instead of h
as the "root" node. Perhaps the author is accounting for a void
return with a dummy-node and side-effect? But in that case the line h.next = t.next
still seems to break the algorithm.