栈
要将链表从尾到头打印,即链表第一个最后打印,链表最后一个先打印,符合“后进先出”,因此可以使用栈结构。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
LinkedList<ListNode> stack = new LinkedList<>();
while(head!=null){
stack.push(head);
head = head.next;
}
int[] ans = new int[stack.size()];
int i = 0;
while(!stack.isEmpty()){
ans[i] = stack.pop().val;
++i;
}
return ans;
}
}