剑指offer 06. 从尾到头打印链表
题目描述
解题思路
利用栈 后进先出 的特性。
class Solution {
public int[] reversePrint(ListNode head) {
//用于遍历链表的指针
ListNode curNode = head;
Stack<Integer> stk = new Stack<>();
//遍历链表,入栈
while (curNode != null) {
stk.push(curNode.val);
curNode = curNode.next;
}
int stackSize = stk.size();
int[] res = new int[stackSize];
//出栈
for (int i = 0; i < stackSize; i++) {
res[i] = stk.pop();
}
return res;
}
}