栈结构特点
栈 是 线性表的其中一种 ,用于 存储固定顺序的元素 , 元素增删 具有 先进后出 的特点。
出栈和入栈
在JavaScript中可以利用数组的 pop() 和 push() 方法可以实现 出栈 和 入栈 。操作如下:
let a = [1, 2, 3, 4, 5] a.pop() // 出栈操作 console.log(a) // [1,2,3,4] a.push(6) // 入栈操作 console.log(a)// [1,2,3,4,6]
面向对象方法封装栈
基于 pop() 和 push() 数组方法。方法设计如下:
pop(): any :若栈不为空,将栈顶元素推出栈。
push(element: any): Stack :将元素推入栈里。
isEmpty(): boolean :判断栈是否为空。
class Stack {
length: number
stack: any[]
constructor() {
this.length = 0
this.stack = []
}
pop(): any {
if (this.isEmpty()) {
throw new Error('Stack is empty.')
} else {
return this.length-- && this.stack.pop()
}
}
push(element: any): Stack {
this.stack.push(element) && this.length++
return this
}
isEmpty(): boolean {
return this.length === 0
}
}
队列结构特点
队列 是 线性表的其中一种 ,用于 存储固定顺序的元素 , 元素增删 具有 先进先出 的特点。
出队和入队
在JavaScript中利用数组的 shift() 和 push() 方法可以实现 出队 和 入队 。操作如下:
let a = [1, 2, 3, 4, 5] a.shift() // 出队操作 console.log(a) // [2, 3, 4, 5] a.push(6) // 入队操作 console.log(a)// [2,3,4,5, 6]
面向对象方法封装队列
基于 shift() 和 push() 数组方法。方法设计如下:
dequeue(): any :若队列不为空,将队列首元素推出队列。
enqueue(element: any): Queue :将元素推入队列里。
isEmpty(): boolean :判断队列是否为空。
class Queue {
length: number
queue: any[]
constructor() {
this.length = 0
this.queue = []
}
dequeue(): any {
if (this.isEmpty()) {
throw new Error('Queue is empty.')
} else {
return this.length-- && this.queue.shift()
}
}
enqueue(element: any): Queue {
this.queue.push(element) && this.length++
return this
}
isEmpty(): boolean {
return this.length === 0
}
}
本文相关代码已放置我的Github仓库 ?
项目地址:
Algorithmlib|Stack
Algorithmlib|Queue
以上就是数据结构TypeScript之栈和队列详解的详细内容,更多关于TypeScript数据结构栈和队列的资料请关注其它相关文章!
原文地址:https://juejin.cn/post/7179162925385383973
查看更多关于数据结构TypeScript之栈和队列详解的详细内容...