实现栈的代码
package NodeTest;
/**
* @ClassName Stack
* @Description TODO
* @Author 1478
* @Date 2020/6/21 23:19
* @Version 1.0
*/
public class ArrayStack<T> {
private T data[];
private int maxSize;
private int top;
/**
* 初始化栈
* @param maxsize
*/
public ArrayStack(int maxsize){
this.maxSize = maxsize;
data = (T[]) new Object[maxsize];
this.top=-1;
}
/**
* 判断栈空
* @return
*/
public boolean isEmpty(){
return (top==-1);
}
/**
* 判断栈满
* @return
*/
public boolean isFull(){
return (top==maxSize-1);
}
public boolean push(T value)throws Exception{
if (isFull()){
throw new Exception("栈满了");
}
top++;
data[top] =value;
return true;
}
public T pop()throws Exception{
if (isEmpty()){
throw new Exception("栈空了");
}
T temp = data[top];
data[top]=null;
top--;
return temp;
}
public void output(){
for (int i=0;i<data.length;i++){
System.out.print(data[i]+",");
}
System.out.println();
}
}
main函数的写法
package NodeTest;
/**
* @ClassName main
* @Author 14784
* @Date 2020/6/3 17:38
* @Version 1.0
*/
public class main {
public static void main(String[] args) throws Exception{
ArrayStack<Integer> arrayStack =new ArrayStack<>(5);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.push(4);
arrayStack.push(5);
arrayStack.push(6);
arrayStack.output();
arrayStack.pop();
arrayStack.pop();
arrayStack.pop();
arrayStack.pop();
arrayStack.pop();
arrayStack.output();
}
}