public class SequenceStack {
private int stackSize=10;
private int[] stack;
// 栈顶指针
private int top=-1;
public SequenceStack(){
stack = new int[stackSize];
}
public SequenceStack(int stackSize){
this.stackSize=stackSize;
stack = new int[stackSize];
}
/**
* 将元素压入栈中
* @param element
*/
public void push(int element){
if(isFull()){
throw new RuntimeException("栈已满!");
}
stack[++top]=element;
}
/**
* 从栈顶弹出一个元素
* @return
*/
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈此时为空!");
}
return stack[top--];
}
/**
* 查看栈顶元素,不删除
* @return
*/
public int peek(){
if(isEmpty()){
System.err.println("栈此时为空!");
return 0;
}
return stack[top];
}
/**
* 栈是否满了
* @return
*/
private boolean isFull(){
if(top>=stackSize-1){
return true;
}
return false;
}
public boolean isEmpty(){
return top==-1?true:false;
}
@Override
public String toString() {
String str="";
for (int i = 0; i <= top; i++) {
str+=stack[i]+" ";
}
return str;
}
}
Java用数组实现顺序栈
最新推荐文章于 2024-07-19 17:37:28 发布