剑指offer--5.从尾到头打印链表

题目:输入一个链表的头结点,从尾到头反过来打印每个结点的值 

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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值