數(shù)據(jù)結構TypeScript之棧和隊列詳解
棧結構特點
棧是線性表的其中一種,用于存儲固定順序的元素,元素增刪具有先進后出的特點。
出棧和入棧
在JavaScript中可以利用數(shù)組的pop()和push()方法可以實現(xiàn)出棧和入棧。操作如下:
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()數(shù)組方法。方法設計如下:
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中利用數(shù)組的shift()和push()方法可以實現(xiàn)出隊和入隊。操作如下:
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()數(shù)組方法。方法設計如下:
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倉庫 ??
項目地址:
以上就是數(shù)據(jù)結構TypeScript之棧和隊列詳解的詳細內容,更多關于TypeScript數(shù)據(jù)結構棧和隊列的資料請關注腳本之家其它相關文章!
相關文章
FastAdmin表單驗證data-rule插件—Nice-validator的使用方法
FastAdmin的表單驗證data-rule非常方便,也很炫酷,采用的Nice-validator是一款非常強大的表單驗證插件,通過簡單在元素上配置規(guī)則,即可達到驗證的效果,怎么使用Nice-validator插件呢2023-09-09

