Java面试之手写栈,数组实现

关于栈的性质就不多说了,直接上代码

package com.wechuan;

public class ArrayStack {
    private long[]a ;
    private int size; //长度
    private int top;//栈顶


    public  ArrayStack(int maxSize){
        this.size=maxSize;
        this.a=new long[size];
        this.top=-1; //表示空栈
    }

    public void push(int value){  //入栈
        if(isFull()){
            System.out.println("栈已满");
            return;
        }
        a[++top]=value;
    }
    public long peek(){   //返回栈顶内容,不会删除;
        if(isEmpty()){
            System.out.println("栈中没有数据");
            return 0;
        }
        return a[top];
    }
    public long pop(){  //出栈 , 弹出栈顶内容,并删除
        if(isEmpty()){
            System.out.println("栈中没有数据");
            return 0;
        }

        return a[top--];   //top--   表示已经指向下一个元素了,所以并没有真正的删除
    }
    public int size(){
        return top+1;
    }

    public void dispaly(){
        for (int i = top;i>=0;i--) {
            System.out.println(a[i]);
        }
    }

    private boolean isEmpty() {
        return (top==-1);
    }

    private boolean isFull() {
        return (top==size-1);
    }


}

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-04 05:12
瑞雪兆丰年_:可以贴个超级大的校徽,以防HR眼拙
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务