package endual;
public class Stack {
private int top = -1 ; //无数据的时候为-1,数据从0开始
private int size = 0 ; //当前的栈中的数据个数
private int capacity = 10 ; //当前栈的默认存储的个数
private Object[] objs ;
public Stack() {
this.objs = new Object[capacity] ;
}
public int size() {
int temp = this.size ;
return temp ; //返回当前的栈的个数
}
//添加一个数据
public void push(Object obj) {
//先判断下当前栈是不是满了
this.size = this.size() ;
//判断下这个容量是不是超过了当前栈的容量
//如果是的话
if (this.size == this.capacity) { //当前的栈容量已经达到了当前栈的容量了,那么要进行扩充
this.capacity = this.capacity + 10 ; //每次扩充都加10的容量
//那么要创建一个新的数组了,然后将旧的数组赋值给新的数组了
Object[] tempObjs = new Object[this.capacity] ;
for (int i=0; i < objs.length; i++) {
tempObjs[i] = this.objs[i] ;
}
this.top++ ; //栈顶的个数加1
tempObjs[this.top] = obj ;
this.objs = tempObjs ;
}
//如果不是的话
else {
this.top++ ;
this.objs[top] = obj ;
}
this.size++ ; //这个是当前栈的里面的数据个数
}
//拉出来一个数据
public void poll() {
if (this.size == 0) {
System.out.println("栈为空");
return ;
}
Object o = null ;
this.objs[this.top] = o ;
this.top-- ;
this.size-- ;
}
//遍历栈
public void bush() {
for (int i=0; i < this.top+1; i++) {
System.out.println(this.objs[i]);
}
}
}
java 栈(面试够了的)
最新推荐文章于 2024-10-04 09:35:44 发布