剑指offer:从尾到头打印链表

输入一个链表,按链表从尾到头的顺序返回一个ArrayList

遇到这种逆置的问题,一般使用栈的先进后出的特性

public class Solution {
    public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
	ArrayList<Integer> res = new ArrayList<>();
		Stack<Integer> temp = new Stack<>();
		while(listNode!=null){
			temp.add(listNode.val);
			listNode = listNode.next;
		}
		
		while(!temp.isEmpty()){
			res.add(temp.pop());
		}
		return res;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/blzm742624643/p/12229842.html