题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例
输入:head = [1,3,2]
输出:[2,3,1]
方法1:模拟
Java实现1:栈模拟
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int[] res = new int[stack.size()];
int flag = 0;
while (!stack.isEmpty()) {
res[flag++] = stack.pop();
}
return res;
}
}
Java实现2:列表模拟
class Solution {
public int[] reversePrint(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
Collections.reverse(list);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
方法2:递归
题解:https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/solution/mian-shi-ti-06-cong-wei-dao-tou-da-yin-lian-biao-d/
Java实现
class Solution {
List<Integer> list = new ArrayList<>();
public int[] reversePrint(ListNode head) {
reverseAdd(head);
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) res[i] = list.get(i);
return res;
}
public void reverseAdd(ListNode head) {
if (head == null) return;
reverseAdd(head.next);
list.add(head.val);
}
}