/**
* 剑指 Offer 06. 从尾到头打印链表
* @author wsq
* @date 2020/09/08
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
*/
package notsubmit;
import java.util.Deque;
import java.util.LinkedList;
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class ReversePrint {
/**
* 使用栈暂存列表中的元素,借助栈FILO的特点,实现列表从未到头的打印
* @param head
* @return
*/
public int[] reversePrint(ListNode head) {
if(head == null) {
return new int[0];
}
Deque<Integer> stack = new LinkedList<Integer>();
ListNode p = head;
while(p != null) {
stack.push(p.val);
p = p.next;
}
int[] ans = new int[stack.size()];
int i = 0;
while(!stack.isEmpty()) {
ans[i++] = stack.poll();
}
return ans;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode node1 = new ListNode(3);
ListNode node2 = new ListNode(2);
head.next = node1;
node1.next = node2;
ReversePrint rp = new ReversePrint();
int[] ans = rp.reversePrint(head);
for(int item: ans) {
System.out.println(item);
}
}
}
剑指 Offer 06. 从尾到头打印链表
最新推荐文章于 2025-11-24 14:05:54 发布
本文提供了一种使用栈实现链表逆序打印的方法,通过遍历链表将各节点值压入栈中,再利用栈的特性进行逆序输出,适用于链表长度不超过10000的场景。
785

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



