题目描述
输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。
返回的结果用数组存储。
样例
输入:[2, 3, 5]
返回:[5, 3, 2]
算法1
Stack类
栈的先进后出
将元素正序压入栈内,在栈中元素默认先从(最后一个元素)尾部输出
时间复杂度
参考文献
java 代码
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] printListReversingly(ListNode head) {
Stack<Integer> stack=new Stack<>();
int num=0;
while(head!=null){
stack.push(head.val);
num++;
head=head.next;
}
int[] res=new int[num];
while(!stack.empty()){
res[res.length-num]=stack.pop();
num--;
}
return res;
}
}