【问题标题】:Counting items in a Stack ADT计数堆栈 ADT 中的项目
【发布时间】:2015-09-07 11:02:52
【问题描述】:

这是对堆栈中的项目进行计数的好方法吗?我不确定这是否是正确的实现方法

private someList<E> stack;

public int countItems(){

        Stack<E> newStack = new Stack<E>();

        int count = 0;

        while(!stack.isEmpty()){

            newStack.push(this.pop());
            count++;
        }

        for(int i = 0; i < count; i++) {  
            this.push(newStack.pop());
        }
        return count;   

    }

【问题讨论】:

    标签: java list generics stack adt


    【解决方案1】:
    public int count() {
        return stack.size();
    }
    

    为什么要再次发布? 我已经在你的previous 帖子中回答了...

    由于 O(n) 行为,您的做法不是正确的方法! 使用我的解决方案 stack.size() 它在 O(1) 中,因为您唯一需要做的就是询问 ArrayList 它的大小(ArrayList 明确记住它的大小,因此它可以回答立即提出您的问题(无需先计算元素)。

    【讨论】:

    • 你说的对,效率更高。谢谢你的帮助:)
    猜你喜欢
    • 2021-03-05
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    相关资源
    最近更新 更多