输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2] 输出:[2,3,1]
思路:
1. 链表逆转
2. 用栈
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public int[] reversePrint(ListNode head) {
int count = 0;
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
count ++;
}
int[] ints = new int[count];
for (int i = 0; i < count; i++) {
ints[i] = stack.pop();
}
return ints;
}