Implementation of the Stack
// 栈类function Stack () { this.dataStore = []; this.top = 0; // 栈顶位置 相当于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: 栈内元素个数function length () { return this.top;}
Practice one. Stacks can be used to determine if the parentheses in an arithmetic expression match. Write a function that takes an arithmetic expression as a parameter and returns the position where the parentheses are missing. The following is an example of an arithmetic expression with mismatched parentheses: 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个字符是不匹配的括号。
Two. An example of a real-life stack is the Pizzi candy box. Imagine you have a box of Pizzi candies stuffed with red, yellow and white candies, but you don't like yellow candies. Write a program using stacks (possibly multiple stacks) and remove the yellow candies without changing the stacking order of other candies in the box.
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
JavaScript data structures and algorithms-stack Exercises