java 栈(面试够了的)

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]);
}

}



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值