一、定义
1.1 背景
经由过程前面一节《JavaScript数据结构01 – 数组》我们晓得,能够在数组的恣意位置上删除或增加元素。但是,有时候我们还需要一种在增加或删除元素时有更多掌握的数据结构。
有两种数据结构类似于数组,但在增加和删除元素时更加可控。
它们就是栈和行列。
1.2 观点
栈是一种遵照后进先出(LIFO)准绳的有序鸠合。新增加的或待删除的元素都保留在栈的末端,称作栈顶,另一端就叫栈底。
在栈里,新元素都靠近栈顶,旧元素都靠近栈底。
栈也被用在编程言语的编译器和内存中保留变量、要领挪用等,比方函数的挪用栈。
二、栈的完成
2.1 建立一个类来示意栈
这里我照样用组织函数的情势来誊写,人人有兴致能够用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():返回栈里的元素个数
2.2 完成栈中的辅佐要领
// 增加新元素到栈顶
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());
}
2.3 建立实例举行测试
// 建立Stack实例
var stack = new Stack();
console.log(stack.isEmpty()); // true
stack.push(5); // undefined
stack.push(8); // undefined
console.log(stack.peek()); // 8
stack.push(11); // undefined
console.log(stack.size()); // 3
console.log(stack.isEmpty()); // false
stack.push(15); // undefined
stack.pop(); // 15
console.log(stack.size()); // 3
stack.print(); // 5,8,11
stack.clear(); // undefined
console.log(stack.size()); // 0
三、完毕
本文会同步到我的个人博客,完全代码能够到我的github堆栈检察,假如对你有协助的话迎接点一个Star~~