首页 > 其他 > 详细

【剑指offer】逆序输出链表

时间:2018-11-25 14:12:01      阅读:167      评论:0      收藏:0      [点我收藏+]
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
*考察栈的使用
*使用循环输出Stack中内容的时候,不能使用for(int i; i<stack.size();i++)因为stack.size()在数据出栈操作后会变化。
/**
*    public class ListNode {
*        int val;
*        ListNode next = null;
*
*        ListNode(int val) {
*            this.val = val;
*        }
*    }
*
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        Stack<Integer> stack = new Stack<Integer>();
        while(listNode!=null){
            stack.push(listNode.val);
            listNode = listNode.next;
        }
       while(stack.size()!=0){
            result.add(stack.pop());
        }
            
        return result;
    }
}

【剑指offer】逆序输出链表

原文:https://www.cnblogs.com/singular/p/10015251.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!