Java basic operation of the stack

Stack: After first-out

Baidu Encyclopedia:

  Stack (Stack), also known as the stack, which is a linear form of operation is limited. Defining a linear table insertion and deletion operations only in the trailer. This input is called the stack, relatively, and the other end is called the bottom of the stack.

To insert a new element, also known as the stack into the stack, push or push, it is a new element into the top element of the above, making the new top of the stack; remove elements from one stack to stack or also known as unstack, it is

The top element removed, so that the adjacent element becomes the new top of the stack.

public class MyStack {
    private int size;
    private int[] arr;
    private int top;
    //栈的初始化
    public MyStack(int size){
        arr=new int[size];
        this.size=size;
        top=-1;
    }
    //入栈
    public void push(int n){
        if(!isFull()){
            arr[++top]=n;
        }the else { 
            System.out.println ( "full stack - can not continue to push!" ); 
        } 
    } 
    // pop / top element to obtain 
    public  int POP () {
         IF (isEmpty ()) { 
            System.out.println ( "empty stack - the stack is no longer element!" );
             return 0 ; 
        } 
        return ARR [top-- ]; 
    } 
    // determines whether the stack is empty 
    public  Boolean isEmpty () {
         return Top == -. 1 ; 
    } 
    / / is determined whether the stack is full 
    public  Boolean isFull () {
         return top==(size-1);
    }
    //获取栈的长度
    public int getStackLength(){
        return top+1;
    }
    //销毁栈
    public void stackDestroy(){
        top=-1;
    }

    public static void main(String[] args) {
        MyStack myStack=new MyStack(5);
        int i=0;
        while(!myStack.isFull()){
            myStack.push(i++);
        }
        while(!myStack.isEmpty()){
            System.out.println(myStack.pop());
        }
    }
}
Published 84 original articles · won praise 0 · Views 699

Guess you like

Origin blog.csdn.net/qq_38405199/article/details/103527624