在一个答复中有代码将其说明清楚,但是你可能会发现,通过问和回答一些微小的问题(这是The Little Lisper中的方法),更容易从头开始。
n元素列表的反向操作是什么?列表其余部分的倒序,后跟第一个元素。
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;
}