1. 题目描述

2. 思路

3. 代码
- 使用栈,先进后出特性
- 这种先进后出,或者倒序的都可以考虑一下栈
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; } // 构造函数
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
// 这种先进后出,或者倒序的都可以考虑一下栈
Stack<Integer> stack = new Stack<>();
ListNode curNode = head;
while(curNode != null){
stack.push(curNode.val);
curNode = curNode.next;
}
// 必须要先获取stack的大小,因为之后pop后stack大小会变。
int size = stack.size();
int[] res = new int[size];
for(int i = 0; i<size; i++){
res[i] = stack.pop();
}
// 按照下面代码,输出是 3,2,0,就是因为pop之后 i < stack.size()重新获取stack大小了。
// int[] res = new int[stack.size()];
// for(int i = 0; i<stack.size(); i++){
// res[i] = stack.pop().val;
// }
return res;
}
}
该博客主要介绍了如何使用栈这一数据结构来解决链表逆序输出的问题。通过遍历链表,将节点值依次压入栈中,然后从栈中弹出节点值,构建逆序的数组。这种方法充分利用了栈的先进后出特性,实现了链表的反转打印。

被折叠的 条评论
为什么被折叠?



