我的代码:(为了测试写成了Integer类的list)
public static LinkedList<Integer> reverse(LinkedList<Integer> list){
if(list==null){
throw new NullPointerException("无法翻转空列");
}
if(list.size()==1){
return list;
}
int i = list.removeFirst();
reverse(list).add(i);
return list;
}
书上的代码:
public static <T> LinkedList<T> reverse(final LinkedList<T> original){
if(original == null){
throw new NullPointerException("Cannot reverse a null list");
}
if(original.getNext() == null){
final LinkedList<T> next = original.next;
original.next = null;
final LinkedList<T> otherReversed = reverse(next);
next.next = original;
return otherReversed;