计算 Stack ADT 中的项目
Counting items in a Stack ADT
这是计算堆栈中项目的好方法吗?我不确定这是否是正确的实施方法
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;
}
public int count() {
return stack.size();
}
为什么要再次 post 呢?
我已经在你的 post...
中回答了
由于 O(n) 行为,您的做法并不正确!
使用我的解决方案 stack.size()
它在 O(1) 因为你唯一要做的就是询问 ArrayList
它的大小(ArrayList
明确记住它的大小,因此它可以立即回答您的问题(无需先计算元素))。
这是计算堆栈中项目的好方法吗?我不确定这是否是正确的实施方法
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;
}
public int count() {
return stack.size();
}
为什么要再次 post 呢?
我已经在你的
由于 O(n) 行为,您的做法并不正确!
使用我的解决方案 stack.size()
它在 O(1) 因为你唯一要做的就是询问 ArrayList
它的大小(ArrayList
明确记住它的大小,因此它可以立即回答您的问题(无需先计算元素))。