zoukankan      html  css  js  c++  java
  • Javascript与数据结构系列(一)——栈的实现

    栈的实现

    实现一个栈,当务之急是决定存储数据的底层数据结构。这里采用的是数组。 我们的实现以定义 Stack 类的构造函数开始:

    function Stack() {

        this.dataStore = [];

        this.top = 0;

        this.push = push;

        this.pop = pop;

        this.peek = peek;

    }

    我们用数组 dataStore 保存栈内元素,构造函数将其初始化为一个空数组。变量 top 记录 栈顶位置,被构造函数初始化为 0,表示栈顶对应数组的起始位置 0。如果有元素被压入 栈,该变量的值将随之变化。先来实现 push() 方法。当向栈中压入一个新元素时,需要将其保存在数组中变量 top 所对 应的位置,然后将 top 值加 1,让其指向数组中下一个空位置。代码如下所示:

    function push(element) {

        this.dataStore[this.top++] = element;

    }

    这里要特别注意 ++ 操作符的位置,它放在 this.top 的后面,这样新入栈的元素就被放在 top 的当前值对应的位置,然后再将变量 top 的值加 1,指向下一个位置。pop() 方法恰好与 push() 方法相反——它返回栈顶元素,同时将变量 top 的值减 1:

    function pop() {

        return this.dataStore[--this.top];

    }

    peek() 方法返回数组的第 top-1 个位置的元素,即栈顶元素:

    function peek() {

        return this.dataStore[this.top-1];

    }

    如果对一个空栈调用 peek() 方法,结果为 undefined。这是因为栈是空的,栈顶没有任何

    元素。

    有时候需要知道栈内存储了多少个元素。length() 方法通过返回变量 top 值的方式返回栈 内的元素个数:

    function length() {

        return this.top;

    }

    最后,可以将变量 top 的值设为 0,轻松清空一个栈:

    function clear() {

        this.top = 0;

    }

     

    代码归纳

    function Stack() {

        this.dataStore = [];

        this.top = 0;

        this.push = push;

        this.pop = pop;

        this.peek = peek;

        this.clear = clear;

        this.length = length;

    }

    function push(element) {

        this.dataStore[this.top++] = element;

    }

    function peek() {

        return this.dataStore[this.top-1];

    }

    function pop() {

        return this.dataStore[--this.top];

    }

    function clear() {

        this.top = 0;

    }

    function length() {

        return this.top;

    }

    栈的应用

    数制间的相互转换

    可以利用栈将一个数字从一种数制转换成另一种数制。假设想将数字 n 转换为以 b 为基数的数字,实现转换的算法如下。

    • 最高位为 n % b,将此位压入栈。

    • 使用n/b代替n。

    • 重复步骤 1 和 2,直到 n 等于 0,且没有余数。

    • 持续将栈内元素弹出,直到栈为空,依次将这些元素排列,就得到转换后数字的字符串形式。

    使用栈,在 JavaScript 中实现该算法就是小菜一碟。下面就是该函数的定义,可以将数字 转化为二至九进制的数字:

    function mulBase(num, base) {

        var s = new Stack();

        do {

            s.push(num % base);

            num = Math.floor(num /= base);

        } while (num > 0);

        var converted = "";

        while (s.length() > 0) {

            converted += s.pop();

        }

        return converted;

    }

    转自: https://segmentfault.com/a/1190000004920420

    作者:  Vagor

  • 相关阅读:
    request
    href="#"
    可展开收起的客服导航。
    JS添加父节点的方法。
    精简漂亮的导航浮动菜单显示特效演示
    竖排导航
    仿新浪微博
    鼠标滑过改变文字
    滚动函数
    一些常用的兼容函数。
  • 原文地址:https://www.cnblogs.com/-ding/p/6029803.html
Copyright © 2011-2022 走看看