一.实现思路
1)准备一个栈 stack
2)对链表进行遍历
3)将元素按遍历顺序压入到栈中
4)根据栈的特性,先进后出,打印出来的结果就是反向遍历
二.代码实现
//从尾到头打印(遍历)链表
public void printDesc(Node head) {
if (head.next == null) {
System.out.println("链表为空");
}
Stack<Node> stack = new Stack<>();
Node cur = head.next;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}