思路:
1.栈是先进后出,可以不断压栈,最后依次弹出即可。注意for循环中不能用stack.size(),因为栈在弹出过程中size会变化。
2.递归
递推阶段: 每次传入 head.next ,以 head == null(即走过链表尾部节点)为递归终止条件,此时直接返回。
回溯阶段: 层层回溯时,将当前节点值加入列表,即tmp.add(head.val)。
最终,将列表 tmp 转化为数组 res ,并返回即可。
以链表1 -> 2 为例,画的递归示意图。
public 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[] array = new int[size];
// for循环中不能是stack.size(),因为stack.size()会动态变化。
for (int i = 0; i < size; i++) {
array[i] = stack.pop();
}
return array;
}
}
class Solution {
private ArrayList<Integer> tmp;
int[] reversePrint(ListNode head) {
tmp = new ArrayList<Integer>();
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);
}
public static void main(String[] args) {
ListNode head1 = new ListNode(1);
ListNode head2 = new ListNode(2);
head1.next = head2;
head2.next = null;
Solution ss=new Solution();
int[] ints = ss.reversePrint(head1);
for (int anInt : ints) {
System.out.println(anInt);
}
}
}