题意: 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1: 输入:head = [1,3,2] 输出:[2,3,1]
分析: 链表只能从前往后访问, 而题目要求:倒序输出 这种先入后出,我们可以通过栈来实现。
辅助栈法
思路: 1.先要创建一个栈. 如何创建? Stack<ListNode> stack = new Stack<ListNode>();
2.当head != null 时通过循环,将链表元素压入栈中 如何压入? stack.push(head);
3.之后建一个数组, 数组的大小如何确定? int [] res = new int[stack.size()];
4.最后通过for循环将栈中的元素 放入数组中。 如何放入?res [i] = stack.pop().val; 代码实现:
/** * 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<ListNode> stack = new Stack<ListNode>(); //创建一个栈 while(head != null){ stack.push(head); head = head.next; } int [] res = new int[stack.size()]; for(int i = 0; i < res.length; i++){ res [i] = stack.pop().val; } return res; } }