javascript构造一个Stack数据结构

2016-04-13  本文已影响0人  一丁o

stack的第一种含义是一组数据的存放方式,特点为LIFO,即后进先出(Last in, first out)。
分析stack的特点:

/**
 * @file Stack.js
 * @desc 用js实现stack数据结构
 *
 * *************************
 * 用法:
 *  var stack = new Stack();
 *  stack.push([1,2,3]);
 *  stack.push('xxxxx');
 *  var all = stack.displayAll();
 *  console.log(all);
 *
 * *************************
 */

function Stack() {

    // 返回最后插入的一个数据
    this.top = null;

    // 返回栈内数据的长度
    this.size = 0;
}

Stack.prototype = {
    constructor: Stack,

    // 插入一个数据,放在栈的最后一个位置
    push: function (data) {
        var node = {
            data: data,
            next: null
        };
        node.next = this.top;
        this.top = node;
        this.size++;
    },

    // 返回最后的一个数据
    peek: function () {
        return this.top === null ? null : this.top.data;
    },

    // 从栈里取出最后的一个数据,与peek的区别:peek只读取,pop返回并移除最顶层的数据
    pop: function () {
        if (this.top === null) return null;
        var out = this.top;
        this.top = this.top.next;
        if (this.size > 0) this.size--;
        return out.data;
    },

    // 清楚栈内的数据
    clear: function () {
        this.top = null;
        this.size = 0;
    },

    // 显示站内的所有数据
    displayAll: function () {
        if (this.top === null) return null;
        var arr = [];
        var current = this.top;
        for (var i = 0, len = this.size; i < len; i++) {
            arr[i] = current.data;
            current = current.next;
        }
        return arr;
    }
};


上一篇下一篇

猜你喜欢

热点阅读