题目
思路
利用栈后进先出的特性。
正向将链表节点全部压入栈中,再一个个弹出来,那么得到自然就是这个链表的从尾到头部的打印。
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack=new Stack<>();
ListNode p=head;
while(p!=null){
stack.push(p.val);
p=p.next;
}
int []ans=new int [stack.size()];
int idx=0;
while(!stack.isEmpty()){
ans[idx++]=stack.pop();
}
return ans;
}
}