简单栈的实现

package jing.able.impl;

/**
 * @author: panjing
 * @describe:
 * @date: 2019/4/14
 * @time: 15:07
 */
public interface IMyStack {
    // 将 item 压入栈中
    void push(int item);
    // 返回栈顶元素,并且出栈
    int pop();
    // 返回栈顶元素,但不出栈
    int peek();
    // 判断这个栈是否为空栈
    boolean empty();
    // 返回元素个数
    int size();
}
  66  MyStack.java 
@@ -0,0 +1,66 @@
package jing.able.dao;

import jing.able.impl.IMyStack;

/**
 * @author: panjing
 * @describe:   简单栈的实现
 * @date: 2019/4/14
 * @time: 15:08
 */

public class MyStack implements IMyStack {
    private int[] elem;
    private int top; //保存得是当前可以存放数据源数的下标
    private int usedSize;
    //默认栈的容量
    private static final int DEFAULT_SIZE=10;  //栈的长度
    public MyStack(){
        this.elem = new int[DEFAULT_SIZE];
        this.top = 0;
        this.usedSize = 0;
    }

    public boolean isFull(){
        return this.top== this.elem.length;
    }
    @Override
    public void push(int item) {
        if(isFull()) {
          throw new UnsupportedOperationException("栈为满");
        }
        this.elem[this.top++] =item;
    }

    @Override
    public int pop() {
       if (empty()){
           throw new UnsupportedOperationException("栈为空");
       }
       int data = this.elem[this.top-1];
       this.usedSize--;
       this.top--;
       return data;
    }

    @Override
    public int peek() {
        if (empty()){
            throw new UnsupportedOperationException("栈为空");
        }
        return this.elem[this.top-1];
    }

    @Override
    public boolean empty() {
        if (this.top == 0) {
            return true;
        }
        return false;
    }

    @Override
    public int size() {
        return this.usedSize;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值