Data Structures and Algorithms --- Stack

Introduction stack:
the stack is a first-in last-out ordered list.
Stack: Change end, including insertion and deletion
bottom of the stack: the fixed end

Stack application scenarios:
1, subroutine call: before the jump to subroutine, will be the address of the next instruction onto the stack until the address is removed again after the subroutine to return to the original program.
2, the process recursively: and the like subroutine calls, in addition to storing the address of the next instruction, and parameters, and other data into the variable region of the stack.
3. [infix expressions are converted transfected with the postfix expression evaluated]
4, the binary tree traversal
5, the depth-first search pattern

Analog array Stack:
Thinking Analysis:
1, using an analog array stack
2, showing the definition of a top stack is initialized to -1
. 3, when data is added to the stack, top ++; Stack [top] = Data;
. 4, the stack operation, int val = stack [top] ; return val;

//定义一个ArrayStack表示栈
class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    //栈慢
    public boolean isFull() {
        return top == maxSize-1;
    }

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

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

    //出栈-pop
    public int pop() {
        if (isEmpty()) {
            System.out.println("栈空,无法出栈");
        }
        int value = stack[top];
        top--;
        return value;  //value是出栈的数据
    }

    //显示,遍历时需要从栈顶开始显示
    public void disPlay() {
        if (isEmpty()) {
            System.out.println("栈空");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }
}

 

 

Published 51 original articles · won praise 14 · views 2319

Guess you like

Origin blog.csdn.net/qq_41185460/article/details/103074465