前言
其实感觉这都不算算法题,不过每天时间有限,也就记录一下了,(ps:程序员简洁风,以后就上题解题说个人思路,嗯,珍爱生命,远离小菜)
题
固定数组实现栈结构及队列结构
基础知识
- 栈:后进先出 可以抽象为一个子弹夹,只有一个出入口
- 队列:先进先出 可以抽象为一个排队,出入口分别在队首和队尾
解题思路
- 实现栈
- 用一个变量指针指向出入口,即永远指向最新数据的索引的变量(index)
- 用size变量表达栈中实际数据量
- 考虑栈空、栈满等问题throw出异常
- 实现队列
- star变量指向添加时的索引的变量,end指向弹出时的索引的变量
- 用一个size变量使得star和end进行解耦,使得边界问题转化成队列长度与size的比较
- 考虑队列空、队列满等问题throw出异常
代码实现
//固定数组实现栈结构
class arrStrack{
constructor(initSize){
if(initSize<0){
throw new Error('栈长度不能为负数')
}
this.initSize = initSize; //栈的长度
this.index = -1; //永远指向最新数据的索引的变量
this.arr = [];
this.size = 0;//实际数据长度
}
/**
*
* @param {数组初始大小} initSize
*/
push(ele){
if((this.index+1) == this.initSize){
throw new Error('栈溢出')
}
this.size++;
this.arr[++this.index]=ele;
}
pop(){
if(this.size==0) throw new Error('栈为空')
this.index--;
return this.arr[--this.size];
}
}
let strack = new arrStrack(3);
strack.push('hhh');
console.log(strack.pop())
//固定数组实现队列结构
class arrQueue{
constructor(initSize){
if(initSize<0){
throw new Error('队列长度不能为负数')
}
this.initSize = initSize; //队列的长度
this.star = 0; //指向添加时的索引的变量
this.end = 0;//指向弹出时的索引的变量
this.arr = [];
this.size = 0;//实际数据长度
}
push(ele){
if(this.size >= this.initSize) throw new Error('队列溢出');
this.arr[this.star++] = ele;
this.star = (this.star+1) >this.initSize ? 0 : this.star++;
}
poll(){
if(this.size == 0) throw new Error('队列为空');
this.end = (this.end+1) > this.initSize ? 0 :this.end++;
size--;
}
}