首页 > IT职业 > IT图书 > JavaScript数据结构02 - 栈
通过前面一节《JavaScript数据结构01 - 数组》我们知道,可以在数组的任意位置上删除或添加元素。然而,有时候我们还需要一种在添加或删除元素时有更多控制的数据结构。
有两种数据结构类似于数组,但在添加和删除元素时更为可控。
它们就是栈和队列。
栈是一种遵循后进先出(LIFO)原则的有序集合。新添加的或待删除的元素都保存在栈的末尾,称作栈顶,另一端就叫栈底。
在栈里,新元素都靠近栈顶,旧元素都接近栈底。
栈也被用在编程语言的编译器和内存中保存变量、方法调用等,比如函数的调用栈。
这里我还是用构造函数的形式来书写,大家有兴趣可以用ES6的Class来重写一遍。
// Stack类function Stack () { this.items = []; this.push = push; this.pop = pop; this.peek = peek; this.isEmpty = isEmpty; this.clear = clear; this.size = size; this.print = print;
}
栈里面有一些声明的方法:
push(element):添加一个(或几个)新元素到栈顶
pop():移除栈顶的元素,同时返回被移除的元素
peek():返回栈顶的元素,不对栈做任何修改
isEmpty():如果栈里没有任何元素就返回true,否则返回false
clear():移除栈里的所有元素
size():返回栈里的元素个数
// 添加新元素到栈顶function push (element) { this.items.push(element);
}// 移除栈顶元素,同时返回被移除的元素function pop () { return this.items.pop();
}// 查看栈顶元素function peek () { return this.items[this.items.length - 1];
}// 判断是否为空栈function isEmpty () { return this.items.length === 0;
}// 清空栈function clear () { this.items = [];
}// 查询栈的长度function size () { return this.items.length;
}// 打印栈里的元素function print () { console.log(this.items.toString());
}
// 创建Stack实例var stack = new Stack(); console.log(stack.isEmpty()); // truestack.push(5); // undefinedstack.push(8); // undefinedconsole.log(stack.peek()); // 8stack.push(11); // undefinedconsole.log(stack.size()); // 3console.log(stack.isEmpty()); // falsestack.push(15); // undefinedstack.pop(); // 15console.log(stack.size()); // 3stack.print(); // 5,8,11stack.clear(); // undefinedconsole.log(stack.size()); // 0
本文会同步到我的个人博客,完整代码可以到我的github仓库查看,如果对你有帮助的话欢迎点一个Star~~
原文链接:https://segmentfault.com/a/1190000015768412
原文作者:liuxuan
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4383/viewspace-2805393/ ,如需转载,请注明出处,否则将追究法律责任。