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

  

posted @ 2020-01-22 22:26  DXYE  阅读(143)  评论(0编辑  收藏  举报