从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
核心思想:使用一个栈,依次访问链表结点,将值入栈。再依次出栈添加到数组中即可
/**
* 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<Integer>();
int nums = 0;
while(head != null){
stack.push(head.val);
head = head.next;
nums++;
}
int[] num = new int[nums];
for(int i = 0; i < nums; i++){
num[i] = stack.pop();
}
return num;
}
}