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());
    }

}

 


版权声明:本文为nosprings原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。