首页 > 编程语言 > 详细

JAVA实现栈

时间:2015-03-23 09:41:33      阅读:248      评论:0      收藏:0      [点我收藏+]
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();

    }
}

JAVA实现栈

原文:http://blog.csdn.net/github_20066005/article/details/44539407

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!