Java基础:数据结构,实现简单栈结构

public class Stack {
    
    private int   size; // 定义栈大小
    private int[] stack;// 使用int数组来模拟一个栈结构
    private int   top;
    private int   bottom=0; // bottom == 0 栈低
    
    // 类的构造方法,构造一个空的栈
    public Stack(int size) {
        this.size = size;  // this代表当前对象
        this.stack = new int[this.size];
        this.top = this.bottom; // 当top == bottom 代表当前的栈是空的
    }
    
    // 判断栈是否是空
    public boolean isEmpty() {
        if(this.top == this.bottom) {
            return true;
        }
        return false;
    }
    
    public boolean isFull() {
        if(this.top == this.size) {
            return true;
        }
        return false;
    }
    
    // 压栈处理 线程同步 synchronized加锁
    public synchronized void push(int data) {
        if(!isFull()) {
            stack[top] = data;  // 将数据压入栈中
            top++;
        }else {
            throw new IllegalStateException("Stack is overflow!");
        }
    }
    
    // 出栈处理
    public synchronized int pop() {
        if(!isEmpty()) {
            top--;
            return stack[top]; // 出栈,可以认为当前位置为空了
        }else {
            throw new IllegalStateException("Stack is empty!");
        }
    }
    
    
    public static int sum(int num) {
        // 递归的退出条件
        if(num == 1) {
            return 1;
        }
        return num + sum(num - 1);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 函数调用栈,函数调用栈是有大小限制的
        // sum(1000000);
        
        // 定义栈: LIFO last in first out
        Stack stack = new Stack(10);
        stack.push(11);
        stack.push(12);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(6);
        stack.push(7);
        stack.push(8);
        stack.push(9);
        stack.push(10);
        // 超出了栈大小
        // stack.push(100);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值