public class ArrayStack {
private int stack[]; //用数组模拟栈,入栈push,出栈pop
private int maxSize; ///栈的最大容量
private int top=-1; //栈顶,没有元素时为-1
//定义完属性后要写构造方法
public ArrayStack(int maxSize)
{
this.maxSize=maxSize;
stack=new int [this.maxSize]; //数组初始化
}
public boolean isFull() //判断栈是否已经满,由于是数组,所以索引maxSize-1就是最大数
{
return top==maxSize-1; //入栈之前先判断是否已经满
}
public boolean isEmpty() //判断栈是否为空,出栈之前先判断是否为空
{
return top==-1;
}
public void push(int value) //入栈操作
{
if(isFull())
{
System.out.println("栈已经满");
}
top++; //入栈时先top++,再添加元素
stack[top]=value;
}
public int pop() //出栈操作
{
if(isFull())
System.out.println("栈已经空");
int value=stack[top]; //出栈时先取得元素,再top--
top--;
return value;
}
public void list() //遍历栈,
{
if(isEmpty())
System.out.println("栈为空");
for(int i=top;i>=0;i--) //从栈顶开始i=top
{
System.out.printf("stack["+i+"]"+"=%d\t",stack[i]);
}
}
public int peek() //返回栈顶元素,但不是pop 因为数组是int类型
{
return stack[top];
}
}
测试代码
public class ArrayStackTest {
public static void main(String[] args) {
ArrayStack arraystack=new ArrayStack(10);
for(int i=1;i<=10;i++)
{
arraystack.push(i);
}
arraystack.list();
int value=arraystack.pop();
System.out.println("value= "+value);
}
}