leetcode链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,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) {
ListNode node = head;
Stack<Integer> stack = new Stack<>();
while(node != null){
stack.push(node.val);
node = node.next;
}
int length = stack.size();
int[] res = new int[length];
for(int i=0;i<length;i++){
res[i] = stack.pop();
}
return res;
}
}