从尾到头打印链表

题解方法

  • 先进后出,实现转置

核心代码

1
2
3
4
5
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
1
2
3
4
5
6
int sum = stack.size();
int[] res = new int[sum];

for (int i = 0; i < sum; i++) {
res[i] = stack.pop();
}

题目来源

剑指 Offer 06. 从尾到头打印链表 - 力扣(LeetCode)