思路:①栈。先进后出,将原链表所有节点压入栈中,再依次弹出,实现逆序打印。②递归。访问节点时,先递归输出后面的节点,再输出自身节点。
//栈
public class Test{
public int[] reversePrint (ListNode head){
Stack<ListNode> stack = new Stack<>();
while (head != null){ //所有节点入栈
stack.push(head);
head = head.next;
}
int[] res = new int[stack.size()];
for (int i = 0; i < res.length; i++){
res[i] = stack.pop().val; //所有节点出栈
}
return res;
}
}
//递归
public class Test{
int[] res;
int i = 0, j = 0;
public int[] reversePrint (ListNode head){
recur (head); //进入递归
return res;
}
public void recur (ListNode head){
if (head == null){ //base case
res = new int[i]; //遍历链表,当到达链表尾节点时,数组res的长度为i
return;
}
i++; //遍历链表时i不断增加,相当于计算链表长度
recur (head.next); //不断向后递归
res[j] = head.val; //向前回溯,res[0]即为原链表尾结点
j++;
}
]