【发布时间】:2019-07-03 19:04:36
【问题描述】:
我正在尝试编写一个方法 public static void removeDownTo (StackX stack, long n):它将所有值从堆栈中弹出,但不包括它看到的等于第二个参数的第一个元素。如果没有一个相等,则将堆栈留空。
我试图通过达到 n 值弹出堆栈的上半部分来解决问题。但是堆栈没有排序,因此会导致一些问题。
public class StackX {
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
//--------------------------------------------------------------
public StackX(int s) // constructor
{
maxSize = s; // set array size
stackArray = new long[maxSize]; // create array
top = -1; // no items yet
}
//--------------------------------------------------------------
public void push(long j) // put item on top of stack
{
if (!isFull())
stackArray[++top] = j; // increment top, insert item
else
System.out.println("Can't insert, stack is full");
}
//--------------------------------------------------------------
public long pop() // take item from top of stack
{
if(!isEmpty())
return stackArray[top--]; // access item, decrement top
else
System.out.print("Error: Stack is empty. Returning -1");
return -1;
}
//--------------------------------------------------------------
public long peek() // peek at top of stack
{
if (isEmpty()){
System.out.print("stack is empty");
}
return stackArray[top];
}
//--------------------------------------------------------------
public boolean isEmpty() // true if stack is empty
{
return (top == -1);
}
//--------------------
public boolean isFull() // true if stack is full
{
return (top == maxSize-1);
}
//--------------------------------------------------------------
public void removeDownTo (StackX stack, long n){
for(int i = 0; stackArray[i] < n; i++){
stack.pop();
}
for(int j = 0; stackArray[j] <= maxSize; j++){
System.out.println(stackArray[j]);
}
}
}
公共类 StackApp {
public static void main(String[] args) {
StackX theStack = new StackX(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);
while( !theStack.isEmpty()){ // until it's empty,
theStack.removeDownTo(theStack, 40);
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
} // end main()
} // 结束类 StackApp
我希望看到 60 80,但结果却是 60 20。
【问题讨论】:
标签: java