数据结构与算法(Java版)_08_栈的学习与代码实现

栈(Stack),其为线性结构,元素在其内部操作规则是先进后出,其有栈顶栈底

添加元素为入栈 push,取出元素为出栈 pop。

代码实现:

package dataStructureAtShangGuiGu;

import java.util.Scanner;

public class StackDemo {

    public static void main(String[] args) {
        MyStack myStack = new MyStack(4);
        Scanner sc = new Scanner(System.in);
        while(true) {
            sop("-----------------------------------");
            sop("1、显示栈");
            sop("2、将一个元素出栈");
            sop("3、输入一个元素并将其入栈");
            sop("4、exit");
            sop("-----------------------------------");
            int select = sc.nextInt();
            switch(select) {
                case 1:
                    myStack.show();
                    break;
                case 2:
                    int element = myStack.pop();
                    if(-1!=element) {
                        sop(element);
                    }
                    break;
                case 3:
                    myStack.push(sc.nextInt());
                    break;
                case 4:
                    System.exit(0);
                    
            }
            
        }
    }
    private static void sop(Object obj) {
        System.out.println(obj);
    }
}
class MyStack{
    public int top;
    public int[] stack;
    public int maxSize;
    public MyStack(int maxSize) {
        this.top = -1;
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }
    public boolean isEmpty() {
        return top == -1;
    }
    public boolean isFull() {
        return top == maxSize-1;
    }
    public void push(int element) {
        if(this.isFull()) { 
            this.sop("栈已满,无法执行push操作!");
            return;
        };
        stack[++top] = element;
    }
    public int pop() {
        if(this.isEmpty()) {
            this.sop("栈是空的,无法执行pop操作!");
            return -1;
        };
        int element = stack[top];
        stack[top--] = 0;
        return element;
    }
    public void show() {
        if(this.isEmpty()) { 
            this.sop("当前栈是空的!");
            return;
        }
        for(int i=stack.length-1;i>=0;i--) {
            this.sop(this.stack[i]);
        }
    }
    private void sop(Object obj) {
        System.out.println(obj);
    }
}

 

posted @ 2021-11-02 22:32  曾经沧海难为水。  阅读(36)  评论(0编辑  收藏  举报