簡單談談棧

美圖

1、前言

計算機程序離不開算法和數據結構,數據結構這門學科就是爲了讓計算機可以以更加高效,簡單,便捷的方式來存儲和使用數據而產生的。本文簡單介紹棧(Stack)和隊列(Queue)的實現html

2、圖解

圖解

3、線性表

一、 順序存儲結構:用一段地址連續的存儲單元依次存儲線性表的數據元素
二、 鏈式存儲結構:用一組任意的存儲單元存儲線性表的數據元素,這組存儲單元能夠連續,也能夠不連續,空間與內存沒有線性關係java

4、棧

一、只容許在一端進行插入和刪除操做的線性表算法

二、 實現的功能瀏覽器

  • push:在最頂層加入數據。
  • pop:返回並移除最頂層的數據。
  • peek:返回最頂層數據的值,但不移除它。
  • empty:返回一個布爾值,表示當前stack是否爲空棧。

2-一、初始化數據結構

private int[] arr;
    //常量用大寫
    private final static int SIZE = 1;
    //棧的當前指針
    private int index;

    //構造器沒有參數的
    public StackDemo() {
        arr = new int[SIZE];
        index = -1;
    }

2-二、pushide

//入棧
private void push(int target){
    if (index == SIZE){
        throw  new  StackOverflowError();
    }else {
        //剛開始爲-1,要前加
        arr[++index] = target;
    }
}

2-三、peek指針

//返回棧頂元素
private int peek(){
    if (index == -1){
        throw new StackOverflowError();
    }else {
        return arr[index];
    }
}

2-四、emptycode

//判空
    private boolean empty(){
        if (index == -1){
            return true;
        }
        return false;
    }

三、代碼實現htm

import java.util.Arrays;

/**
 *
 * @author buer
 * @date 2019/1/20
 */
public class StackDemo {
    private int[] arr;
    //常量用大寫
    private final static int SIZE = 1;
    //棧的當前指針
    private int index;

    //構造器沒有參數的
    public StackDemo() {
        arr = new int[SIZE];
        index = -1;
    }

    //入棧
    private void push(int target){
        if (index == SIZE){
            throw  new  StackOverflowError();
        }else {
            //剛開始爲-1,要前加
            arr[++index] = target;
        }
    }

    //出棧
    private int pop(){
        if (index == -1){
            throw new StackOverflowError();
        }else {
            return arr[index--];
        }
    }

    //返回棧頂元素
    private int peek(){
        if (index == -1){
            throw new StackOverflowError();
        }else {
            return arr[index];
        }
    }

    //判空
    private boolean empty(){
        if (index == -1){
            return true;
        }
        return false;
    }
    public static void main(String[] args) {
        StackDemo stackDemo = new StackDemo();
        stackDemo.push(1);
        System.out.println(stackDemo.toString());
        stackDemo.pop();
        System.out.println(stackDemo.toString());

    }

    @Override
    public String toString() {
        return "StackDemo{" +
                "arr=" + Arrays.toString(arr) +
                ", index=" + index +
                '}';
    }
}

應用

一、括號匹配blog

二、中綴表達式(人類的思考)和後綴表達式(計算機的計算)

三、遞歸

四、瀏覽器的前進後退功能

參考資料

https://zh.wikipedia.org
https://www.zhihu.com/question/21318658
http://www.ruanyifeng.com/blog/2013/11/stack.html

相關文章
相關標籤/搜索