栈java实现之线性存储源码
class Stack<T>{
private int size=0;//栈大小
private final int default_length=20;
private int length;//栈容量
private Object[] o;
//初始化
public Stack(){
length = default_length;
o = new Object[length];
}
public Stack(T data,int init_length){
length = init_length;
o = new Object[length];
o[0] = data;
size++;
}
//
public int getLength(){
return size;
}
//入栈
public void push(T data){
if(size+1>length){
while(size+1 > length){
length <<=1;
}
Object[] temp = new Object[length];
int i = o.length;
while(i-->=0){
temp[i]=o[i];
o[i] = null;
}
o = temp;
}
o[size++]=data;
}
//出栈
public T pop(){
@SuppressWarnings("unchecked")
T olddata = (T) o[size-1];
o[--size] = null;
return olddata;
}
//只返回栈顶元素
@SuppressWarnings("unchecked")
public T peek(){
return (T) o[size-1];
}
//判空
public boolean isEmpty(){
if(size >0){
return false;
}else{
return true;
}
}
//清空
public void clear(){
while(size>0){
o[--size] = null;
}
}
@Override
public String toString() {
if(size == 0){
return "[]";
}else{
StringBuffer sb = new StringBuffer("[");
int i=0;
while(i<size)
sb.append(o[i++]+",");
return sb.delete(sb.length()-1, sb.length()).toString()+"]";
}
}
}