JavaScript data structures and algorithms-stack Exercises

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.