美文网首页前端技术讨论
javaScript数据结构--栈

javaScript数据结构--栈

作者: 安然_她 | 来源:发表于2019-05-13 13:58 被阅读0次

栈是一种遵循后进先出(LIFO last in first out)原则的有序集合,新添加或待删除的元素都保存在栈的末尾,成为栈顶,另一端叫栈底。

实现一个栈的数据结构:

function Stack() {

    var items = [];

    this.push = function(element) {

        items.push(element);

    }

    this.pop = function() {

        items.pop();

    }

    this.peek = function() {

        return items[items.length-1]

    }

    this.size = function() {

        return items.length;

    }

    this.isEmpty = function() {

        return items.length > 0 ? false: true

    }

    this.clear = function() {

        items = [];

    }

}

const s = new Stack();

s.push("a");

s.push(2);

console.log(s.peek()); // 2

console.log(s.size()); // 2

console.log(s.isEmpty()); // false

s.pop();

console.log(s.peek()); // a

console.log(s.size()); // 1

s.clear();

console.log(s.size()); // 0

console.log(s.isEmpty()); // true

相关文章

网友评论

    本文标题:javaScript数据结构--栈

    本文链接:https://www.haomeiwen.com/subject/lbmlaqtx.html