數據結構TypeScript之棧和隊列詳解
棧結構特點
棧是線性表的其中一種,用于存儲固定順序的元素,元素增刪具有先進后出的特點。
出棧和入棧
在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倉庫 ??
項目地址:
以上就是數據結構TypeScript之棧和隊列詳解的詳細內容,更多關于TypeScript數據結構棧和隊列的資料請關注腳本之家其它相關文章!
相關文章
Typescript使用裝飾器實現接口字段映射與Mock實例
這篇文章主要為大家介紹了Typescript使用裝飾器實現接口字段映射與Mock實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
TypeScript數組實現棧與對象實現棧的區(qū)別詳解
這篇文章主要為大家介紹了TypeScript數組實現棧與對象實現棧的區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
rollup?cli開發(fā)全面系統(tǒng)性rollup源碼分析
這篇文章主要為大家介紹了rollup?cli開發(fā)全網系統(tǒng)性rollup源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01

