《劍指offer》編程題-逆序輸出鏈表
#要求:輸入一個鏈表,按鏈表從尾到頭的順序返回一個ArrayList。
#逆序輸出鏈表,類似於經典的鏈表逆置題目 利用鏈表簡單的特點,逐次向後遞歸即可,遞歸終止的條件是結點是否爲空,到達最後一個節點時,再往後next,但已經null了,將最後一個存入arraylist,並逐步遞歸回去。
本題更像在考察arraylist的應用
#Java代碼:
import java.util.ArrayList;
public class Solution {
ArrayList<Integer> arrayList=new ArrayList<Integer>();
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
if(listNode!=null){
this.printListFromTailToHead(listNode.next);
arrayList.add(listNode.val);
}
return arrayList;
}
}
附鏈表逆置並返回頭結點的遞歸代碼:
public Node Reverse(Node head)
{
if(head==null||head.next==null)
return head;
Node tmp=head.next;
Node newHead=Reverse(head.next);
tmp.next=head;
head.next=null;
return newHead;
}