【发布时间】:2011-05-02 20:38:19
【问题描述】:
我正在查看这篇帖子中的解决方案Reversing a linked list in Java, recursively
我复制了以下解决方案之一。我已经实现了,效果很好。
public ListNode Reverse(ListNode list)
{
if (list == null) return null; // first question
if (list.next == null) return list; // second question
// third question - in Lisp this is easy, but we don't have cons
// so we grab the second element (which will be the last after we reverse it)
ListNode secondElem = list.next;
// bug fix - need to unlink list from the rest or you will get a cycle
list.next = null;
// then we reverse everything from the second element on
ListNode reverseRest = Reverse(secondElem);
// then we join the two lists
secondElem.Next = list;
return reverseRest;
}
然而,我不明白的是最后几行。
secondElem.next = list;
return reverseRest;
看来我们根本没有返回 secondElem?但是我通过代码进行了调试,看起来 secondElem 已经在 reverseRest 中。这是因为它是 Java 中的值引用,并且在应用 secondElem.Next=list 时会自动更新?
【问题讨论】:
标签: java collections