Look at the animation algorithm: stack stack

Introduction

The stack should be a very simple and very useful data structure. The characteristic of the stack is FILO or LIFO.

In fact, the structure of many virtual machines is a stack. Because the stack is very effective in implementing function calls.

Today we will take a look at the structure and usage of the stack.

The composition of the stack

A stack is an ordered linear list that can only be inserted or deleted at one end. This end is called the top end.

To define a stack, we need to implement two functions, one is push, which means push, and the other is pop, which means pop.

Of course, we can also define some other auxiliary functions, such as top: get the topmost node on the stack. isEmpty: Determine whether the stack is empty. isFull: Determine whether the stack is full or the like.

First look at the animation of the stack:

Look at the animation of popping again:

Implementation of the stack

How is a stack with such a function implemented?

Generally speaking, the stack can be implemented with an array or a linked list.

Use arrays to implement stacks

If an array is used to implement the stack, we can use the last node of the array as the head of the stack. In this way, only the last node in the array needs to be modified when operating the push and pop stacks.

We also need a topIndex to save the position of the last node.

The implementation code is as follows:

public class ArrayStack {

    //实际存储数据的数组
    private int[] array;
    //stack的容量
    private int capacity;
    //stack头部指针的位置
    private int topIndex;

    public ArrayStack(int capacity){
        this.capacity= capacity;
        array = new int[capacity];
        //默认情况下topIndex是-1,表示stack是空
        topIndex=-1;
    }

    /**
     * stack 是否为空
     * @return
     */
    public boolean isEmpty(){
        return topIndex == -1;
    }

    /**
     * stack 是否满了
     * @return
     */
    public boolean isFull(){
        return topIndex == array.length -1 ;
    }

    public void push(int data){
        if(isFull()){
            System.out.println("Stack已经满了,禁止插入");
        }else{
            array[++topIndex]=data;
        }
    }

    public int pop(){
        if(isEmpty()){
            System.out.println("Stack是空的");
            return -1;
        }else{
            return array[topIndex--];
        }
    }
}

Use dynamic arrays to implement stacks

In the above example, our array size is fixed. In other words, the stack is limited in capacity.

What if we want to build a stack of unlimited capacity?

It's very simple. When pushing, if the stack is full, we can expand the underlying array.

The implementation code is as follows:

public void push(int data){
        if(isFull()){
            System.out.println("Stack已经满了,stack扩容");
            expandStack();
        }
        array[++topIndex]=data;
    }

    //扩容stack,这里我们简单的使用倍增方式
    private void expandStack(){
        int[] expandedArray = new int[capacity* 2];
        System.arraycopy(array,0, expandedArray,0, capacity);
        capacity= capacity*2;
        array= expandedArray;
    }

Of course, there are many ways to expand the array, here we choose the multiplication method.

Use linked list to achieve

In addition to using arrays, we can also use linked lists to create stacks.

When using a linked list, we only need to operate on the head node of the linked list. Insertion and deletion are the head nodes that are processed.

public class LinkedListStack {

    private Node headNode;

    class Node {
        int data;
        Node next;
        //Node的构造函数
        Node(int d) {
            data = d;
        }
    }

    public void push(int data){
        if(headNode == null){
            headNode= new Node(data);
        }else{
            Node newNode= new Node(data);
            newNode.next= headNode;
            headNode= newNode;
        }
    }

    public int top(){
        if(headNode ==null){
            return -1;
        }else{
            return headNode.data;
        }
    }

    public int pop(){
        if(headNode ==null){
            System.out.println("Stack是空的");
            return -1;
        }else{
            int data= headNode.data;
            headNode= headNode.next;
            return data;
        }
    }

    public boolean isEmpty(){
        return headNode==null;
    }
}

The code address of this article:

learn-algorithm

This article has been included in http://www.flydean.com/10-algorithm-stack/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "Program those things", know technology, know you better!


程序那些事
Spring,区块链,密码学,分布式,多线程等教程 欢迎关注我的公众号:程序那些事,更多精彩等着您!

欢迎访问我的个人网站:www.flydean.com

813 声望
421 粉丝
0 条评论
推荐阅读
还在stream中使用peek?不要被这些陷阱绊住了
自从JDK中引入了stream之后,仿佛一切都变得很简单,根据stream提供的各种方法,如map,peek,flatmap等等,让我们的编程变得更美好。

flydean

数据结构与算法:二分查找
一、常见数据结构简单数据结构(必须理解和掌握)有序数据结构:栈、队列、链表。有序数据结构省空间(储存空间小)无序数据结构:集合、字典、散列表,无序数据结构省时间(读取时间快)复杂数据结构树、 堆图二...

白鲸鱼9阅读 5.2k

openKylin 0.9.5版本正式发布,加速国产操作系统自主创新进程!
2023年1月12日,中国桌面操作系统根社区openKylin(开放麒麟)正式发布openKylin 0.9.5操作系统版本。此版本充分适应5G时代需求,打通平板,PC等设备,实现多端融合,弥补了国产操作系统的短板,有效推动国产操作...

openKylin6阅读 7.9k

封面图
不会数学的程序员,只能走到初级开发工程师!
在我还是初级程序员时,每天也都粘贴着代码和包装着接口。那个阶段并没有意识到数学能在编程中起到什么作用,就算学了数学的部分知识,也没法用到编程中。但后来随着编程越来越久,逐步接手核心代码块开发时候,...

小傅哥3阅读 853

封面图
杨辉三角的5个特性,一个比一个牛皮!
杨辉三角按照杨辉于1261年所编写的《详解九章算法》一书,里面有一张图片,介绍此种算法来自于另外一个数学家贾宪所编写的《释锁算书》一书,但这本书早已失传无从考证。但可以肯定的是这一图形的发现我国不迟于1...

小傅哥3阅读 1.7k

stackoverflow 提问:“计算两个整数的最小公倍数的最有效方法是什么?”
作者:小傅哥博客:[链接]源码:[链接]沉淀、分享、成长,让自己和他人都能有所收获!😄一、前言嘿,小傅哥怎么突然讲到最大公约数了?这么想你肯定是没有好好阅读前面章节中小傅哥讲到的RSA算法,对于与欧拉结果...

小傅哥3阅读 1.6k

封面图
DeepMind 发布强化学习通用算法 DreamerV3,AI 成精自学捡钻石
内容一览:强化学习是多学科领域的交叉产物,其本质是实现自动决策且可做连续决策。本文将介绍 DeepMind 最新研发成果:扩大强化学习应用范围的通用算法 DreamerV3。关键词:强化学习 DeepMind 通用算法

超神经HyperAI1阅读 898

封面图

欢迎访问我的个人网站:www.flydean.com

813 声望
421 粉丝
宣传栏