栈,是一种特殊的数组,其特点是先进后出,当我们对数组的一些功能加以限制便可以创建出一个栈
目标
对于栈我们要实现的基本功能如下:
- 只能从数组的末尾添加元素(入栈)
- 检查栈是否为空和它的大小
- 只能从数组的末尾添加元素(弹出)
- 查看栈顶
- 清空栈
- 打印栈的内容
代码
class stack
{
constructor()
{
this.count = 0;
//items属性是JavaScript对象,是一个键值对集合
//用于栈的索引和元素值的保存
this.items()={};
}
//入栈
push(element)
{
this.items[this.count] = element;
this.count++;
}
//查看栈是否为空和它的大小
isEmpty()
{
return this.count === 0;
}
size()
{
return this.count;
}
//弹出
pop()
{
//查看栈是否为空
if(this.count.isEmpty())
{
return undefined;
}
this.count--;
//先保存一下删除的元素值,以便后面的return返回
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
//查看栈顶
//因为count相当于length属性,所以访问栈顶时要记得count-1
peek()
{
if(this.count.isEmpty())
{
return undefined;
}
return this.items[this.count-1];
}
//清空栈
//将值复原为构造函数中的使用值即可
clear()
{
this.count = 0;
this.items = [];
}
//打印栈的内容
toString()
{
if(this.count.isEmpty())
{
return ' ';
}
//打印时需要栈底的第一个元素作为字符串的初始值来迭代整个栈的键
let a = '${this.items[0]}';
//进入迭代
for (let i = 1; i < this.count; i++)
{
a = '${a}','${this.items[i]}';
}
return a;
}
}