反转链表

题目链接-来源:力扣(LeetCode)

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

思路:

题目不要求重组链表,只要求反向打印内容,那么用栈存储内容再逐个打印即可。

实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[] reversePrint(ListNode head) {
Stack<ListNode> s = new Stack<>();
while (head != null) {
s.push(head);
head = head.next;
}
int[] ret = new int[s.size()];
int i = 0;
while (!s.isEmpty()) {
ret[i] = s.pop().val;
i++;
}
return ret;
}
}