我试图写一个方法公共静态无效removeDownTo(StackX栈,长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。
既然你是相当新的节目,你的老师给你一个任务,那就是要解决很简单。您应密切坚持其词。这些话给你的主要线索。
你应该定义该方法:
public static void removeDownTo (StackX stack, long n)
在这里,这个词static
是很重要的。这意味着,该方法应该不会进入StackX
类。 (说明应提到这个地方。)如果你的任务已经到方法添加到StackX
类,它看起来会是这样的:
public void removeDownTo (long n)
这两种方法之间的区别在于,后者可以访问StackX
类的所有的实现细节,这是变量maxSize
,stackArray
和top
。
但是,你的任务是不同的,你的方法应该是static
,这意味着它没有访问这些实施细则。所有你能做的就是调用被标记为public
方法。有其中5,他们都开始以小写字母。只使用这些方法5,你应该解决这个难题,因为你写的:
它会弹出堆栈的所有值下,但不包括它看到等于所述第二参数的第一要素。如果没有相等,保持堆栈空。
通过上面列出的5种方法,你可以看到一个堆栈只允许很少的操作。想想一个大摞书的。你不能只取一本书从中间,你唯一可以做的事情是看在堆栈的顶部。这是a stack的性质。
你试过:
我已经通过到达n值从堆栈弹出的上半部分试图关闭部分问题。但堆栈不排序所以它会导致一些问题。
这个任务是比你想象的要简单得多。这是不是在所有的排序。更加紧密地按照说明的话。最后,您removeDownTo
方法应该是5号线长,从开始到结束。这意味着在大括号里面,有你需要编写代码只有3行。