从尾到头打印链表

一种解法是利用反转链表的方式

然后 把反转的链表依次添加到result的结果当中去

public static ArrayList<Integer> printListFromTailToHead(ListNode head){
		if(head == null) return null;
		List<Integer> temp = new ArrayList<Integer>();
		if(head.next == null) { 
			
			temp.add(head.val);
			return (ArrayList<Integer>) temp;
		}
		head = reverseListNode(head);
		while(head != null){
			temp.add(head.val);
			head = head.next;
		}
		return (ArrayList<Integer>)temp;
	}
	public static ListNode reverseListNode(ListNode head){
		ListNode prev = null;
		ListNode after = head.next;
		while(after != null){
			head.next = prev;
			prev = head;
			head = after;
			after = after.next;
		}
		head.next = prev;
		return head;
	}

上面是自己想到的,但是觉得有点麻烦两次遍历了链表但是网上的解法也都是两次遍历链表。
有一个关于Stack实现的解法

解法二 利用栈

栈中常用的几个方法
栈的定义 Stack stack = new Stack<>();
push
pop
isEmpty()

	public static ArrayList<Integer> dealWithStack(ListNode head){
		ArrayList<Integer> result = new ArrayList<>();
		if(head == null) return result;
		Stack<Integer> stack = new Stack();
		while(head != null){
			stack.push(head.val);
			head = head.next;
		}
		while(!stack.isEmpty()){
			result.add(stack.pop());
		}
		return result;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值