package com.chb.Stack;
public class testStack {
public static void main(String[] args) {
ArrayStack stack=new ArrayStack(10);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.show();
System.out.println(stack.peek());
stack.pop();
stack.show();
}
}
class ArrayStack{
private int maxSize;//栈的大小
private int[]stack;
private int top=-1;
public ArrayStack(int maxSize) {
super();
this.maxSize = maxSize;
stack =new int[maxSize];
}
//栈满
public boolean isFull() {
return top==maxSize-1;
}
//栈空
public boolean isEmpty() {
return top==-1;
}
//入栈
public void push(int n) {
if(isFull()) {
System.out.println("栈满");
return;
}
stack[++top]=n;
}
//出栈
public int pop() {
if(isEmpty()) {
throw new RuntimeException("栈空,没有数据");
}
return stack[top--];
}
//取栈顶元素
public int peek() {
return stack[top];
}
//遍历栈
public void show() {
if(isEmpty()) {
System.out.println("栈空,没有数据");
return;
}
for (int i = top; i >=0; i--) {
System.out.print(stack[i]+" ");
}
System.out.println();
}
}
运行结果: