棧的實現(xiàn)
// 棧類
function Stack () {
this.dataStore = [];
this.top = 0; // 棧頂位置 相當(dāng)于length,不是索引。
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}
// push: 入棧
function push (element) {
this.dataStore[this.top++] = element;
}
// pop: 出棧
function pop () {
return this.dataStore[--this.top];
}
// peek: 取棧頂元素
function peek () {
return this.dataStore[this.top - 1];
}
// clear: 清空棧
function clear () {
this.top = 0;
}
// length: 棧內(nèi)元素個數(shù)
function length () {
return this.top;
}
練習(xí)
一. ??梢杂脕砼袛嘁粋€算術(shù)表達(dá)式中的括號是否匹配。編寫一個函數(shù),該函數(shù)接受一個算術(shù)表達(dá)式作為參數(shù),返回括號缺失的位置。下面是一個括號不匹配的算術(shù)表達(dá)式的例子:2.3 + 23 / 12 + (3.14159 * 0.24。
function findWrongBrace (express) {
let s = new Stack();
for (let i = 0; i < express.length; ++i) {
if (express[i] === `(`) {
s.push(i);
} else if (express[i] === `)`) {
s.pop();
}
}
return `${express}的第${s.peek() + 1}個字符是不匹配的括號。`;
}
// 示例
console.log(findWrongBrace(`2.3 + 23 / 12 + (3.14159 * 0.24`)); // 2.3 + 23 / 12 + (3.14159 * 0.24的第17個字符是不匹配的括號。
二. 現(xiàn)實生活中棧的一個例子是佩茲糖果盒。想象一下你有一盒佩茲糖果,里面塞滿了紅色,黃色和白色的糖果,但是你不喜歡黃色的糖果。使用棧(有可能用到多個棧)寫一段程序,在不改變盒內(nèi)其他糖果疊放順序的基礎(chǔ)上,將黃色糖果移除。
let Candy = `rywrryywwrrryyywww`, newCandy = ``; // 模擬糖果
let s = new Stack();
let len = Candy.length;
while (len--) {
if (Candy[len] !== `y`) {
s.push(Candy[len]);
}
}
while (s.length()) {
newCandy += s.pop();
}
console.log(newCandy); // rwrrwwrrrwww
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。