https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
Java (借助栈
/**
* 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<Integer> stack = new LinkedList<Integer>(); //辅助栈
//元素入栈O(n)
while(head != null){
stack.addLast(head.val);
head = head.next;
}
//根据栈大小创建数组
int[] res = new int[stack.size()];
//栈内元素弹出到数组中O(n)
for(int i=0;i<res.length;i++)
res[i] = stack.removeLast();
return res;
}
}
Java (递推
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//递推
ArrayList<Integer> tmp = new ArrayList<Integer>();
public int[] reversePrint(ListNode head) {
recur(head);
int[] res = new int[tmp.size()];
for(int i = 0; i < res.length; i++)
res[i] = tmp.get(i);
return res;
}
void recur(ListNode head) {
if(head == null) return; //头节点为空判断
recur(head.next);
tmp.add(head.val);
}
}