/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/*
1.用一个栈,来实现倒序输出(本题)
2.改变结构,将链表先翻转,后输出
*/
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<Integer> stack = new LinkedList<>();
//将链表元素压入栈
while(head!= null){
stack.addLast(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
//将栈中的元素 出栈,赋值给数组res
for(int i = 0;i < res.length;i++){
res[i] = stack.removeLast();
}
return res;
}
}
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
//将链表元素压入栈
while(head!= null){
stack.push(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
//将栈中的元素 出栈,赋值给数组res
for(int i = 0;i < res.length;i++){
res[i] = stack.pop();
}
return res;
}
}