class Deque {
constructor() {
this.list = {}
this.count = 0
this.lowestrCount = 0
}
//在双端队列前端添加
addFront(el){
if(this.isEmpty()){
this.addBack(el)
} else if (this.lowestrCount>0){
this.lowestrCount--
this.list[this.lowestrCount] = element
}else {
for (let i =this.count;i >0;i--){
this.list[i]=this.list[i-1]
}
this.count++
this.lowestrCount=0
this.list[0] = el
}
}
//在双端队列后端添加
addBack(el){
this.list[this.count] = element
this.count++
}
//删除双端队列前端移除第一个元素
removeFront (){
if (this.isEmpty()) {
return undefined
}
const result = this.list[this.lowestCount]
delete this.list[this.lowestCount]
this.lowestCount++
return result
}
//删除双端队列后端移除最后一个元素
removeBack(){
if (this.isEmpty()) {
return undefined
}
const result = this.list[this.count]
delete this.list[this.count]
this.count--
return result
}
//返回双端队列前端第一个元素
peekFront(){
if (this.isEmpty()) {
return undefined
}
return this.list[this.lowestCount]
}
//返回双端队列后端第一个元素
peekBack () {
if (this.isEmpty()) {
return undefined
}
return this.list[this.count]
}
//判断双端队列是不是为空
isEmpty() {
return this.count-this.lowestrCount===0
}
//清空队列
clear () {
this.list = {}
this.count = 0
this.lowestCount=0
}
//字符串方法
toString () {
if (this.isEmpty()) {
return ''
}
let str = `${this.list[this.lowestCount]}`
for (let i = this.lowestCount + 1; i < this.count; i++){
str+=`,${this.list[i]}`
}
return str
}
}
JavaScript数据结构之双端队列
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 栈(Stack) 栈:又称为栈或堆叠,是计算机科学中的一种抽象数据类型,只允许在有序的线性数据集合的一端(称为堆栈...
- 一、队列的定义 队列也是数据结构的其中一种,和栈相反的是。队列是只允许在一端进行插入,在另一端进行删除的线性表。 ...
- 数据结构和算法是计算机技术的基本功之一,北京大学的课程深入浅出,使用Python作为载体简化了编程难度。最近浏览了...
- 栈 栈:是一种容器,可存入数据元素、访问元素、删除元素,它的特点在于只能允许在容器的一端进行加入数据和输出数据的运...