輸入一個鏈表的頭結點,按照 從尾到頭 的順序返回節點的值。算法
返回的結果用數組存儲。數組
樣例
輸入:[2, 3, 5]
返回:[5, 3, 2]code
將鏈表遍歷一遍,保存到List或者Stack中,再遍歷一遍List或Stack便可。
時間複雜度O(n)get
class Solution { public int[] printListReversingly(ListNode head) { if(head == null) { return null; } List<Integer> list = new ArrayList<Integer>(); ListNode p = head; while(p != null) { list.add(p.val); p = p.next; } int[] resArr = new int[list.size()]; int resArrCurIdx = 0; for(int i=list.size()-1; i>=0; i--) { resArr[resArrCurIdx] = list.get(i); resArrCurIdx++; } return resArr; } }