在stackoverflow上看到一个好的方案。http://stackoverflow.com/questions/354875/reversing-a-linked-list-in-java-recursively
Three questions to ask:
- What is the reverse of null (the empty list)? null.
- What is the reverse of a one element list? the element.
- What is the reverse of an n element list? the reverse of the second element on followed by the first element.
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;
}
另一篇好东西在这里http://blog.csdn.net/feliciafay/article/details/6841115