package linklist;
/** * JAVA实现栈的数据结构(先进后出) * 使用数组的形式来存储 * @author zhang * */
public class Stack {
private Object[] stackElement;
private int length = 16;
private int size = 0;
private int postion = 0; //游标位置
public Stack(){}
public Stack(int length){
this.length = length;
}
/** * 判断是不是已经满了 * @return */
private boolean isFul(){
if(postion == size){
return true;
}else{
return false;
}
}
/** * 如果装满了,则申请新的空间,把原来的空间上的复制到新的空间 */
private void copy(){
Object ele[] = new Object[length+16]; //每次扩增16
for(int i=0;i<stackElement.length;i++){
ele[i] = stackElement[i]; //复制
}
this.length = length+16;
stackElement = ele;
}
/** * 进栈 * @param element */
public void push(Object element){
if(stackElement == null){
stackElement = new Object[length];
stackElement[postion] = element;
postion++;
}else{
if(isFul() == true){
copy(); //创建新的空间,增加存储区域
stackElement[postion] = element;
postion++;
} else {
stackElement[postion] = element;
postion++;
}
}
}
/** * 出栈 * @return */
public Object pop(int pos){
if(stackElement != null && pos>=0 && pos<=postion){
return stackElement[pos];
}
return null;
}
/** * 遍历所有 */
public void display(){
for(int i=postion;i>0;i--){
Object obj = pop(i);
System.out.println(obj.toString());
}
}
public static void main(String[] args) {
Stack stack = new Stack();
for(int i=0;i<10;i++){
stack.push(i);
}
stack.display();
}
}
转载于:https://my.oschina.net/zhanghongbin01/blog/547728