使用一维数组编码实现一个栈(Stack)类,要求提供以下操作:
(1)boolean isEmpty():判断栈当前是否为空;
(2)入栈操作void push(int);
(3)出栈操作Object pop();
(4)int getTop();取堆栈当前栈顶的数据元素并返回。
代码
public class Stack {
private int maxSize;
private int[] stackArr;
private int top;
public Stack(int t)
{
this.maxSize = t;
top = -1;
stackArr = new int[t];
}
public int Pop()
{
return stackArr[top--];
}
public int getTop()
{
return stackArr[top];
}
public void Push(int t)
{
stackArr[++top] = t;
}
public boolean Isempty()
{
return (top == -1);
}
public boolean Isfull()
{
return (top == maxSize-1);
}
}
public class Test {
public static void main(String[] args)
{
Stack test = new Stack(10);
int i =0;
test.Push(100);
System.out.println(test.getTop());
while(!test.Isfull())
{
test.Push(i);
i++;
}
while(!test.Isempty())
{
System.out.println(test.Pop());
i++;
}
}
}
运行结果: