【发布时间】:2021-06-13 18:30:29
【问题描述】:
我需要编写arrayImpOfStack.java,然后编写一个main方法来读取一个数字序列并使用堆栈操作以相反的顺序打印它们
如何在输出中反转数字?
我有两节课
1 级
class stackAr
{
int elements [];
int top; // is the index of the cell containing the last elements added to the stack.
stackAr(int maxlength) {top = maxlength; elements = new int[maxlength]; };
// initially the value of the variable top = maxlength which means the stack is empty
// So the variable top must be decremented before pushing new element, which means
// the first element is pushed at cell numbered maxlength-1
// the second element is pushed at the cell numbered maxlength-2
// the third element is pushed at the cell numbered maxlength-3
// an so on the stack is full when top = 0
void push(int x)
{ if (top == 0) System.out.println("the Stack is Full ");
else elements[--top] = x;
}
Boolean isEmpty() // Note the stack is empty when top = elements.length which is the maxlength
{
if (top == elements.length) return true; else return false;
}
void pop() // pop increment the variable top to ignore the last element added to the stack
{
if (!isEmpty()) top++ ;
else System.out.println("Stack is Empty ");
}
int Top() // return the last element added to the stack
{if (!isEmpty()) return elements[top];
else {System.out.println("Stack is Empty "); return top;}
}
void MakeNull() {top = elements.length;} // make the stack empty
}
我有主课
public static void main(String[] args) {
stackAr s = new stackAr(20);
s.push(1);
s.push(9);
s.push(2);
s.push(10);
while(!s.isEmpty())
{
System.out.println(s.Top());
s.pop();
}
【问题讨论】: