Stack 栈 简单了解

什么是 栈?

计算机科学中是一种数据结构。

栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

特点

栈模型.png
  • 先进先出
  • 主要操作有 进栈push 出栈 pop

js简单模拟 stack 类

class Stack {
    constructor() {
            this.data = []; //栈元素
            this.topIndex = 0; //顶级栈元素下标
        }
        //进栈
    push() {
            let args = [...arguments];
            args.forEach(arg => this.data[this.topIndex++] = arg);
            return this.topIndex;
        }
        //出栈
    pop() {
            if (this.topIndex === 0) throw new Error('当前栈为空');
            let top = this.data[this.topIndex - 1];
            this.data = this.data.slice(0, -1);
            this.topIndex = this.topIndex - 1;
            return top; //出栈元素
        }
        //清栈
    clear() {
            this.topIndex = 0;
            this.data = [];
            return this.topIndex;
        }
        //获取顶级元素
    top() {
            if (this.topIndex === 0) throw new Error('当前栈为空');
            return this.data[this.topIndex - 1];
        }
        //是否为空栈
    isEmpty() {
            return this.topIndex === 0;
        }
        //栈长度
    size() {
        return this.topIndex;
    }
}
console.log('push', stack.push(1, 2, 3));//push 3
console.log('isEmpty', stack.isEmpty());//isEmpty false
console.log('size', stack.size());//size 3
console.log('pop', stack.pop());//pop 3
console.log('top', stack.top());//top 2
console.log('clear', stack.clear());//clear 0
console.log('isEmpty', stack.isEmpty());//isEmpty true

栈的两个小应用

  • 十进制 转 二进制
const convert = (num, base) => {
    let result = '',
        stack = new Stack();
    while (num > 0) {
        stack.push(num % base);
        num = Math.floor(num / base);
    }
    while (!stack.isEmpty()) {
        result += stack.pop();
    }
    return +result;
}
console.log('convert', convert(11, 2));//convert 1011
  • 翻转字符串
const revers = (str) => {
    let stack = new Stack(),
        result = '';
    str = str.toString();
    for (let i = 0; i < str.length; i++) {
        stack.push(str.charAt(i))
    }
    while (!stack.isEmpty()) {
        result += stack.pop();
    }
    return result;
}

console.log('revers', revers(131241));//revers 142131
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 如需转载, 请咨询作者, 并且注明出处.有任何问题, 可以关注我的微博: coderwhy, 或者添加我的微信: ...
    coderwhy阅读 19,654评论 5 48
  • 第2章 基本语法 2.1 概述 基本句法和变量 语句 JavaScript程序的执行单位为行(line),也就是一...
    悟名先生阅读 4,199评论 0 13
  • 1、线性表、栈和队列等数据结构所表达和处理的数据以线性结构为组织形式。栈是一种特殊的线性表,这种线性表只能在固定的...
    雾熏阅读 2,473评论 0 10
  • 栈和队列是两种应用非常广泛的数据结构,它们都来自线性表数据结构,都是“操作受限”的线性表。 栈 栈(Stack):...
    karlsu阅读 680评论 0 1
  • 脱去厚重的冬装,也不管初春的寒冷,径自换上那一袭棉布旗袍,亚麻的底色上开满了妖艳的桃花,脚踩一双草鞋,脚趾裸露在微...
    苏默Echo阅读 528评论 0 1