题目:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
举例:已知链表:1->2->3,输出:[3,2,1]
思路:使用栈,栈具有先进后出的特点。
代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
int size = 0;
Stack<Integer> stack = new Stack<>();
while(head !=null){
size++;
stack.push(head.val);
head = head.next;
}
int[] nums = new int[size];
size = 0;
while(!stack.empty()){
nums[size++] = stack.pop();
}
return nums;
}
}