我正在看这篇文章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已经在reverseRest内.这是因为它是Java中的值引用,并且当应用secondElem.Next = list时它会自动更新吗?