棧是一種后進(jìn)先出的LIFO原則的有序集合侠草。
我們使用數(shù)組來保存棧里面的元素
創(chuàng)建Stack類
function Stack() {
//選擇數(shù)組保存棧中的內(nèi)容
let items = []; //添加一個或者幾個元素到棧頂
this.push = function (element) {
items.push(element); };
//移除棧頂元素同時返回被移除的元素
//arrayObject.pop()方法用于刪除并返回數(shù)組的最后一個元素另假。
this.pop = function () { return items.pop(); };
//判斷棧是否為空
this.isEmpty = function () { return items.length === 0; }
//返回棧頂?shù)脑厍也粚W鋈魏涡薷?
this.peek = function () { return items[items.length-1]; };
//返回棧的元素個數(shù)
this.size = function () { return items.length; };
//清空棧
//也可以多次調(diào)用pop方法進(jìn)行清空
this.clear = function () { items = []; };
//打印棧
this.print = function () { console.log(items.toString()); };}
使用class將Stack函數(shù)轉(zhuǎn)換成Stack類
class Stack {
constructor(){
this.items = [];
}
push(element){
this.items.push(element);
}
//移除棧頂元素同時返回被移除的元素
//arrayObject.pop()方法用于刪除并返回數(shù)組的最后一個元素吁津。
pop () {
return this.items.pop();
}
//判斷棧是否為空
isEmpty () {
return this.items.length === 0;
}
//返回棧頂?shù)脑厍也粚W鋈魏涡薷?
peek () {
return this.items[this.items.length-1];
}
//返回棧的元素個數(shù)
size () {
return this.items.length;
}
//清空棧
//也可以多次調(diào)用pop方法進(jìn)行清空
clear () {
this.items = [];
}
//打印棧
print () {
console.log(this.items.toString());
}
}
使用Symbol實現(xiàn)類
let_items =Symbol();
class Stack {
constructor () {
this[_items] = []
}
//Stack方法
}
使用WeakMap實現(xiàn)
const items = new WeakMap();
class Stack{
constructor(){
items.set(this, []);
}
push(element){
let s = items.get(this);
s.push(element);
}
pop(){
let s = items.get(this);
let r = s.pop();
return r;
}
//其他方法
}
有興趣可以加入Nodejs交流群猜谚,和大佬們一起成長5裥健J锊!
群號:348108867
圖片.png