輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
示例 1:
輸入:head = [1,3,2]
輸出:[2,3,1]
方法1:
使用ArrayList集合
class Solution {
public int[] reversePrint(ListNode head) {
ListNode temp = head;
int length = 0;
List<Integer> list = new ArrayList<>();
while(temp !=null){
length++;
list.add(temp.val);
temp = temp.next;
}
int[] res = new int[length];
for(int i=0;i<length;i++){
res[i] = list.get(length-i-1);
}
return res;
}
}
運行結果
方法2: 符合棧的數據結構,先進出,用棧實現
public int[] reversePrint(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode temp = head;
while(null != temp){
stack.push(temp);
temp = temp.next;
}
int length = stack.size();
int[] result = new int[length];
for(int i = 0;i<length;i++){
result[i] = stack.pop().val;
}
return result;
}
執行結果:
時間複雜度: O(n) n代表鏈表的長度
空間複雜度:O(n) n表示使用棧的長度(使用棧的長度取決於鏈表的長度,鏈表長度爲n,所以棧使用的空間長度也是n)