棧 是一種遵循 後進先出(LIFO) 原則的有序集合。新添加和待刪除的數據都保存在棧的同一端棧頂,另外一端就是棧底。新元素靠近棧頂,舊元素靠近棧底。git
咱們須要本身建立一個棧,而且這個棧包含一些方法。算法
function Stack() {
let items = [];
this.push = function(element) {
items.push(element);
};
this.pop = function() {
let s = items.pop();
return s;
};
this.peek = function() {
return items[items.length - 1];
};
this.isEmpty = function() {
return items.length == 0;
};
this.size = function() {
return items.length;
};
this.clear = function() {
items = [];
}
}
複製代碼
可是這樣的方式在建立多個實例的時候爲建立多個items的副本。就不太合適了。 用ES如何6實現Stack類了。能夠用WeakMap實現,並保證屬性是私有的。bash
let Stack = (function() {
const items = new WeakMap();
class Stack {
constructor() {
items.set(this, []);
}
getItems() {
let s = items.get(this);
return s;
}
push(element) {
this.getItems().push(element);
}
pop() {
return this.getItems().pop();
}
peek() {
return this.getItems()[this.getItems.length - 1];
}
isEmpty() {
return this.getItems().length == 0;
}
size() {
return this.getItems().length;
}
clear() {
this.getItems() = [];
}
}
return Stack;
})();
複製代碼
棧能夠解決十進制轉爲二進制的問題、任意進制轉換的問題、平衡園括號問題、漢羅塔問題。數據結構
// 例子十進制轉二進制問題
function divideBy2(decNumber) {
var remStack = new Stack(),
rem,
binaryString = '';
while (decNumber > 0) {
rem = Math.floor(decNumber % 2);
remStack.push(rem);
decNumber = Math.floor(decNumber / 2);
}
while(!remStack.isEmpty()) {
binaryString += remStack.pop().toString();
}
return binaryString;
}
// 任意進制轉換的算法
function baseConverter(decNumber, base) {
var remStack = new Stack(),
rem,
binaryString = '',
digits = '0123456789ABCDEF';
while (decNumber > 0) {
rem = Math.floor(decNumber % base);
remStack.push(rem);
decNumber = Math.floor(decNumber / base);
}
while(!remStack.isEmpty()) {
binaryString += digits[remStack.pop()].toString();
}
return binaryString;
}
複製代碼