【发布时间】:2019-07-03 19:50:35
【问题描述】:
我正在做我的教授告诉全班做的这个练习。 “写一个方法 public static void removeDownTo (StackX stack, long ob):它将所有值弹出 堆栈到但不包括它看到的等于第二个参数的第一个元素。如果 没有一个是相等的,将堆栈留空。”
这是我的代码。
StackX类:
public class StackX {
private static int maxSize; // size of stack array
private static 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
{
stackArray[++top] = j; // increment top, insert item
/** if (isFull() ) {
System.out.println("Push error: Stack is full. Push failed.");
} else {
stackArray[++top] = j;
} */
}
//--------------------------------------------------------------
public long pop() // take item from top of stack
{
return stackArray[top--]; // access item, decrement top
/** if(!isEmpty()) {
return stackArray[top--];
} else {
System.out.println("Error: Stack is empty. Returning -1");
return -1;
}
*/
}
//--------------------------------------------------------------
public long peek() // peek at top of stack
{
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);
}
}
StackApp类:
public class StackApp
{
public static void removeDownTo(StackX stack, long n) {
long x;
while(!stack.isEmpty()) {
x = stack.peek();
stack.pop();
if(stack.isEmpty()) {
if(x==n) {
stack.push(x);
}
}
}
}
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);
// theStack.push(16);
// theStack.push(10);
while( !theStack.isEmpty() ) // until it's empty,
{ // delete item from stack
long value = theStack.pop();
System.out.print(value); // display it
System.out.print(" ");
} // end while
System.out.println("");
removeDownTo(theStack, 60);
System.out.print("");
} // end main()
} // end class StackApp ##
这是它显示的输出: 80、60、40、20。
但是,我认为这个练习要求的输出是 60、40、20。我做错了什么?
【问题讨论】:
-
我认为你错过了你在这里实际做的事情。首先,始终如一地重新格式化您的代码,它必须看起来不错才能被理解。现在,看看“main”方法中的“while”循环,你只是在“弹出”和显示,很明显你会在控制台输出中看到 80、60、40、20。
-
为什么你的
if(x==n)在if(stack.isEmpty())里面检查?为什么在考虑重新添加“downTo”目标之前必须清除堆栈? -
那我不把 removeDownTo(theStack, 60) 放在 while 循环里面吗?
-
@Alice 我需要纠正自己。在 removeDownTo 方法中移除元素后,可以循环(弹出每个元素)Stack 并显示剩余元素。
-
嘿,非常感谢您的帮助!我将使用这些技巧来提高我的编程技能。是的,可以阅读