栈
遵循后进先出原则的有序集合。新添加的元素或待删除的元素都保存在栈的同一端,称为栈顶,另一端为栈底,在栈中,新元素都靠近栈顶,旧元素都靠近栈底
1 class Stack{
2 constructor(){
3 this.count = 0
4 this.items = []
5 }
6 push(element){ // 插入元素
7 this.items[this.count] = element
8 this.count ++
9 }
10 isEmpty(){ // 判断是否为空
11 return this.count === 0
12 }
13 size(){ // 数组长度
14 return this.count
15 }
16 pop(){ // 删除栈顶元素
17 if(isEmpty()){
18 return undefined
19 }
20 this.count--
21 const result = this.items[this.count]
22 delete items[this.count]
23 return result
24 }
25 peek(){ // 查看栈顶元素
26 if(isEmpty()){
27 return undefined
28 }
29 return this.items[this.count-1]
30 }
31 clear(){ // 清空栈
32 this.items = []
33 this.count = 0
34 }
35 toString(){ // toString方法
36 if(isEmpty()){
37 return ""
38 }
39 let objString = `${this.items = [0]}`
40 for(let i = 1; i < this.count; i++){
41 objString = `${objString},${this.items[i]}`
42 }
43 return objString
44 }
45 }
队列
遵循先进先出原则
1 class Queue{
2 // 队列
3 constructor(){
4 this.count = 0 // 长度
5 this.lowestCount = 0 // 头元素索引
6 this.items = {}
7 }
8 enqueue(element){ // 向队列中添加元素,添加到队列末端
9 this.items[this.count] = element
10 this.count ++
11 }
12 isEmpty(){
13 return this.count===0
14 }
15 dequeue(){ // 移除队列中的头元素
16 if(isEmpty()){
17 return undefined
18 }
19 const result = this.items[this.lowestCount]
20 delete this.items[this.lowestCount]
21 this.lowestCount++ // 头元素索引增加一
22 return result
23 }
24 peek(){ // 查询队列头元素
25 if(isEmpty()){
26 return undefined
27 }
28 return this.items[this.lowestCount]
29 }
30 size(){ // 数组长度
31 return this.count - this.lowestCount
32 }
33 clear(){ // 清空数组
34 this.items = {}
35 this.count = 0
36 this.lowestCount = 0
37 }
38 toString(){ // toString方法
39 if(isEmpty()){
40 return ""
41 }
42 let str = `${this.items[this.lowestCount]}`
43 for(let i = this.lowestCount+1; i< this.count; i++){
44 str = `${str},${this.items[i]}`
45 }
46 return str
47 }
48
49 }
双端队列
可自由选择添加/删除头元素还是尾元素
1 class Deque{ // 主要写addFront方法,其余和普通队列无异
2 constructor(){
3 this.count = 0
4 this.lowestCount = 0
5 this.items = {}
6 }
7 isEmpty(){
8 return this.count === 0
9 }
10 addBack(element){ // 加至末尾
11 this.items[this.count] = element
12 this.count++
13 }
14 addFront(element){ // 默认为不能包含负键
15 if(isEmpty()){ // 若队列为空,则直接调用addBack方法
16 addBack(element)
17 }else if(this.lowestCount > 0){ // 若头元素索引大于0,则直接使用最小索引加即可
18 this.lowestCount--
19 this.items[this.lowestCount] = element
20 }else{ // 头元素索引为0且队列不为空,整体向后移位,新元素加至头部
21 for(let i = this.count; i > 0; i--){
22 this.items[i] = this.items[i-1]
23 }
24 this.count++
25 this.items[0] = element
26 }
27
28 }
29 }