【数据结构与算法】顺序栈与链式栈及其实现

关于栈,我们先想一个生活中的例子,就是一摞叠在一起的盘子。我们平时放盘子的时候,都是从下往上一个一个放;取的时候,我们也是从上往下一个一个依次取。后进者先出,先进者后出,这就是典型的栈结构。

栈是一种“操作受限”的线性表,只允许在一端进行插入和删除数据。进行操作的那一段被称为栈顶,与此相对,栈的另一端叫做栈底。栈的操作是按照后进先出的原则进行。

顺序栈

采用顺序存储结构的栈称为顺序栈,需要一块连续的区域来存储存储栈中的元素,因此需要实现知道或估算栈的大小。
顺序栈本质上是简化的顺序表。
顺序栈示意图:

基于数组实现顺序栈

public class ArrayStack {
        //数组
        private String[] items;
        //栈中元素的个数
        private int count;
        //栈的大小
        private int n;

        //初始化数组,申请大小为n的数组空间
        public ArrayStack(int n) {
            this.items = new String[n];
            this.n=n;
            this.count = 0;
        }
        //入栈
        public boolean push(String item){
            //数组空间不够了,直接返回false,入栈失败
            if(count==n){
                return false;
            }
            //将item放到下标为count的位置,并且count加1
            items[count]=item;
            ++count;
            return true;
        }
        //出栈
        public String pop(){
            //栈为空,则直接返回null
            if(count==0){
                return null;
            }
            //返回下标为count-1的数组元素,并且栈中元素个数count减1
            String tmp=items[count-1];
            --count;
            return tmp;
        }
}

测试顺序栈

public class Test {
    public static void main(String[] args) {
        ArrayStack arrayStack=new ArrayStack(5);
        arrayStack.push("1");
        arrayStack.push("2");
        arrayStack.push("3");
        arrayStack.pop();
        arrayStack.pop();
    }
}

栈变化

在这里插入图片描述

链式栈

链式栈本质上是简化的链表
数据成员top是一个指向链式栈的首节点
链式栈示意图:
在这里插入图片描述

基于链表实现链式栈

public class LinkedStack {
    public class Node{
        private String value;
        private Node next;
        public Node(String value,Node node){
            this.value=value;
            this.next=node;
        }
    }
    private Node top=null;
    /**
     * 入栈
     */
    public void push(String value){
        Node newNode=new Node(value,null);
        if(top==null){
        	//栈为空
            top=newNode;
        }else{
            //栈不为空,新节点作为头结点
            newNode.next=top;
            top=newNode;
        }
    }

    /**
     * 出栈
     */
    public String pop(){
        //栈为空,则直接返回null
        if(top==null){
            return null;
        }
        String value=top.value;
        top=top.next;
        return value;
    }
}

测试链式栈

public class Test {
    public static void main(String[] args) {
        LinkedStack linkedStack=new LinkedStack();
        linkedStack.push("1");
        linkedStack.push("2");
        linkedStack.push("3");
        linkedStack.pop();
        linkedStack.pop();
    }
}

栈变换

在这里插入图片描述

原创文章 255 获赞 116 访问量 19万+

猜你喜欢

转载自blog.csdn.net/cxh6863/article/details/103989492