从尾到头打印链表
题目
输入一个链表的头结点,从尾到头反过来打印出每个节点的值。
思路
我们将链表从头到尾压入栈中,然后再将栈中的元素pop出来。
代码
public static void printList(ListNode node){
Stack<Integer> stack=new Stack<Integer>();
while(node!=null){
stack.push(node.val);
node=node.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
}