JavaScript数据结构与算法-栈练习
2024-10-20 11:24:43
栈的实现
// 栈类
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
最新文章
- eclipse下遇到 无法解析类型 javax.servlet.http.HttpServletRequest
- 将salt取到的数据处理
- Simple Shopping Cart By AngularJS
- 如何写好一个UITableView
- Activity小结
- cct软件测试
- C89, C99, C11: All the specifics that I know
- 将数组写入plist文件
- ViewModel从未如此清爽 - 轻量级WPF MVVM框架Stylet
- Visual Studio自动添加头部注释 -C#开发2010-2013验证
- Hive简记
- python 全栈开发,Day5
- bzoj2149拆迁队 斜率优化dp+分治
- 有无序的实数列V[N],要求求里面大小相邻的实数的差的最大值,关键是要求线性空间和线性时间。
- SpringBoot 2.0 pom.xml 配置(热启动)
- 2018 CCPC网络赛 1010 hdu 6447 ( 树状数组优化dp)
- Tomcat9配置SSL连接
- 绚丽而实用的jQuery/CSS3应用及源码
- 从0开始学golang--1.1--连接ms sql server数据库
- IP和java.net.InetAddress类的使用
热门文章
- Java: 获取当前执行位置的文件名/类名/方法名/行号
- Android - 错误:Unable to instantiate application
- Oculus rift DK2 新手使用设置
- Spring 常用注入注解(annotation)和其对应xml标签
- 轻量级代码生成器-OnlyCoder 第一篇
- linux 设置tomcat快捷启动方式
- dos2unix dos文本转换为linux文本 /bin/bas^M:bad interpreter
- android 阿拉伯语下,图库中编辑运动轨迹图片,动画中会显示绿色的图片
- Yarn源码分析之MRAppMaster上MapReduce作业处理总流程(一)
- python第二周数据类型 字符编码 文件处理