题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
题目链接: 从尾到头打印链表
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
思路
可以借助栈这种数据结构实现后进先出的案例。
代码
public static int[] reversePrint(ListNode head) {
if(head==null){
return new int[0];
}
Stack<ListNode> stack=new Stack<>();
ListNode cur=head;
while (cur!=null){
stack.push(cur);
cur=cur.next;
}
int i=0;
int[] res=new int[stack.size()];
while (stack.size()>0){
res[i++]=stack.pop().val;
}
return res;
}