
JavaScript数据结构与算法-栈练习
发布日期:2021-05-09 05:14:08
浏览次数:23
分类:博客文章
本文共 1421 字,大约阅读时间需要 4 分钟。
栈的实现
// 栈类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;}
练习
一. 栈可以用来判断一个算术表达式中的括号是否匹配。编写一个函数,该函数接受一个算术表达式作为参数,返回括号缺失的位置。下面是一个括号不匹配的算术表达式的例子: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个字符是不匹配的括号。
二. 现实生活中栈的一个例子是佩兹糖果盒。想象一下你有一盒佩兹糖果,里面塞满了红色,黄色和白色的糖果,但是你不喜欢黄色的糖果。使用栈(有可能用到多个栈)写一段程序,在不改变盒内其他糖果叠放顺序的基础上,将黄色糖果移除。
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
发表评论
最新留言
路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年04月05日 13时01分06秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
微信小程序setData子元素
2019-03-06
Docker常用操作
2019-03-06
查看已经开放的端口,查看和清理tomcat日志文件
2019-03-06
TX锁处理
2019-03-06
使用UTF8字符集存储中文生僻字
2019-03-06
去除空格函数trim
2019-03-06
11.2.0.4单实例静默安装
2019-03-06
SQL*Net break/reset to client (%)等待事件
2019-03-06
数据泵使用NETWORK_LINK不落地导入数据
2019-03-06
实验之-----------修改oracle实例名
2019-03-06
控制文件
2019-03-06
Oracle text组件安装
2019-03-06
ConcurrentHashMap 源码分析
2019-03-06
在不影响程序使用的情况下添加shellcode
2019-03-06
刷LeetCode的简易姿势
2019-03-06