题目:输入一个链表的头结点,从尾到头反过来打印每个结点的值
public class wr5ListFromTailToHead {
// 栈,每经过一个结点,把该结点放到一个栈中,遍历完链表后,从栈顶输出
public void reversePrint(ListNode head){
if(head==null){
return;
}
Stack<ListNode> stack=new Stack<>();
ListNode current=head;
while(current!=null){
stack.push(current);
current=current.next;
}
while(!stack.isEmpty()){
System.out.println(stack.pop().val+" ");
}
}
// 递归,要实现反过来输出链表,每访问一个结点,先递归输出它后面的结点,再输出该结点自身
// 但当链表非常长的时候,导致函数调用的层级很深,函数调用栈溢出
ArrayList<Integer> list=new ArrayList<>();
public ArrayList<Integer> print(ListNode listNode){
if(listNode!=null){
this.print(listNode.next);
list.add(listNode.val);
}
return list;
}
}