- 题目描述:
- 思路:思路相对简单,利用栈先进后出的特性,先将链表值
push()
入栈,然后建立数组,将栈内值依次pop()
存入数组,返回数组即可。 - 代码
class Solution {
public int[] reversePrint(ListNode head) {
//使用栈,先将链表值push()入栈,然后建立数组,将栈内值pop()存入数组
Stack<ListNode> stack = new Stack();
ListNode temp = head;
while(temp != null){
stack.push(temp);
temp = temp.next;
}
int size = stack.size();
int[] arr = new int[size];
for(int i = 0;i < size;i++){
arr[i] = stack.pop().val;
}
return arr;
}
}