23-咸鱼学Java-Java中的栈

栈的图示
这里写图片描述
代码

/**
 * 栈
 * @author 焦焱
 * 
 */
public class Stack {
    /**
     * 栈顶标记
     */
    int top;
    /**
     * 栈内元素
     */
    int[] elem;
    /**
     * 无参构造
     */
    public Stack()
    {
        this(10);
    }
    /**
     * 有参构造
     * @param size
     */
    public Stack(int size) {
        this.top = 0;
        this.elem = new int[size];
    }

    /**
     * 入栈
     * @param val
     * @return
     */
    public boolean push(int val)
    {   //先判断是否满
        if(isFull()){
            return false;
        }
        //如果不为空,赋值,并且栈顶往上走一位
        this.elem[this.top++] = val;
        return true;
    }
    /**
     * 出栈
     * @return
     */
    public int pop() {
        //先判断是否为空
        if(isEmpty()){
            System.out.println("当前栈为空");
            return -1;
        }
        //返回当前栈顶减一位置的的元素,并且栈顶往下减一。
        return elem[--top];
    }
    /**
     * 获得栈顶元素
     * @return
     */
    public int getTop()
    {   //如果为空返回-1,如果
        return isEmpty()?-1:elem[this.top-1];
    }
    /**
     * 判断是否满
     * @return
     */
    public boolean isFull()
    {
        return top==this.elem.length;
    }
    /**
     * 判断是否空
     * @return
     */
    public boolean isEmpty()
    {
        return top==0;
    }
    /**
     * 显示当前栈内所有元素
     */
    public void show()
    {
        System.out.println("\t栈顶------->栈底");
        System.out.print("当前栈数据为:");
        for (int i = top-1; i >=0; i--) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
}

测试

public static void main(String[] args) {
    Stack t = new Stack();
    int stackLength = 5;
    for (int i = 0; i < stackLength; i++) {
        t.push(i);
    }
    t.show();
    for (int i = 0; i < stackLength; i++) {
        System.out.println(t.pop()+" ");
    }
}   

结果
栈顶------->栈底
当前栈数据为:4 3 2 1 0
4
3
2
1
0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值