Java数据结构之栈以及栈的各种操作

什么是栈:

栈是一种用于存储数据的简单数据结构,有点类似链表或者顺序表(统称线性表),栈与线性表的最大区别是数据的存取的操作,我们可以这样认为栈(Stack)是一种特殊的线性表,其插入和删除操作只允许在线性表的一端进行,一般而言,把允许操作的一端称为栈顶(Top),不可操作的一端称为栈底(Bottom),同时把插入元素的操作称为入栈(Push),删除元素的操作称为出栈(Pop)。若栈中没有任何元素,则称为空栈,栈在java中使用数组实现的,
栈的结构如下图:

这里写图片描述

栈只能从栈顶存取元素,同时先进入的元素反而是后出。

栈的各种操作及其代码实现

class stack{
    int top;
    int []elem;
    public stack(){
        this(10);
    }
    public stack(int size) {
    this.elem=new int [size];
    this.top=0;
        // TODO Auto-generated constructor stub
    }

    //栈是否为满
    public boolean isfull()     
    {
        if(this.top==this.elem.length){
            return true;
        }
        return false;
    }
    //入栈
    public boolean rush(int val){
        if((isfull())){
            return false;
        }
        this.elem[top]=val;
        this.top=top+1;
        return true;


    }//是否为空

    public  boolean isempty(){  
        if(this.top==0){
        return true;
    }
    return false;

    } 
    //出栈
    public void pop(){
        if(isempty()){
            return ;
        }
        --this.top;

    }
    //得到栈顶的元素
    public int gettop(){
        if(isempty()){
            return -1;
        }
        return this.elem[this.top-1];//不能改变top的值,不能进行--top
    }
    //打印栈的全部元素
    public void show(){
        for (int i=0;i<this.top;i++){
            System.out.println(this.elem[i]);
        }
    }
}
public class test3 {
    public static void main(String[] args) {
        stack t1=new stack();
        t1.rush(1);
        t1.rush(3);
        t1.rush(5);
        t1.show();
        System.out.println("栈顶元素为"+t1.gettop());

    }

}

运行结果:
1
3
5
栈顶元素为5

猜你喜欢

转载自blog.csdn.net/qq_37232304/article/details/80210042