/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//用递归的方法来解
int len = 0; //记录链表的长度
int[] res; //返回的数组
int index = 0; //记录数组的下标
public int[] reversePrint(ListNode head) {
//如果头节点为空,说明是个空链表
if (head == null) {
return new int[0]; //返回一个空数组
}
if (head.next == null) { //说明是最后一个节点
res = new int[len + 1]; //如果遍历到尾结点,就根据记录的链表长度创建数组
res[0] = head.val; //将尾结点赋值到数组第一个位置
} else { //如果不是尾结点,就继续遍历,顺便记录链表长度
len++;
reversePrint(head.next);
res[++index] = head.val;
}
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 size = stack.size();
//创建一个数组,用来存放需要放回的节点的值
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i]=stack.pop();
}
return arr;
}
}