Java数据结构与算法

Java数据结构:栈(stack)

2020-07-06  本文已影响0人  Patarw

1.栈的基本介绍

出栈(pop)和入栈(push)的概念(如图所示)


2.栈的一些应用场景

3.使用代码实现栈

public static void main(String[] args) {                 
ArrayStack stack = new ArrayStack(10);
stack.push(1);
stack.push(5);
stack.push(6);
stack.pop();
stack.list();
}
}


//用ArrayStack来表示栈
 class ArrayStack{
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize) {
    this.maxSize = maxSize;
    this.stack = new int[maxSize];
        }

//判断是否栈满
public boolean isFull() {
    return top == maxSize-1;
}

//判断是否栈空
public boolean isEmpty() {
    return top == -1;
}

//入栈,push方法
public void push(int value) {
    if(this.isFull()) {
        System.out.println("栈满,无法入栈");
    }
    top++;
    stack[top] = value;
}

//出栈,pop方法
public int pop() {
    if(this.isEmpty()) {
        throw new RuntimeException("栈空,无法出栈");
    }
    int value = stack[top];
    top--;
    return value;
}

//遍历栈,从栈顶开始
public void list() {
    if(isEmpty()) {
        System.out.println("栈空");
    }
    for(int i = top;i>=0;i--) {
        System.out.println(stack[i]);
    }
}

下一节:递归

https://www.jianshu.com/p/875f4ca945a6

上一篇 下一篇

猜你喜欢

热点阅读