日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

數(shù)據(jù)結(jié)構(gòu)TypeScript之棧和隊列詳解_其它

作者:前端技術(shù)獺 ? 更新時間: 2023-03-26 編程語言

棧結(jié)構(gòu)特點

線性表的其中一種,用于存儲固定順序的元素元素增刪具有先進后出的特點。

出棧和入棧

在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]

面向?qū)ο蠓椒ǚ庋b棧

基于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
    }
}

隊列結(jié)構(gòu)特點

隊列線性表的其中一種,用于存儲固定順序的元素元素增刪具有先進先出的特點。

出隊和入隊

在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]

面向?qū)ο蠓椒ǚ庋b隊列

基于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
    }
}

本文相關(guān)代碼已放置我的Github倉庫 ??

項目地址:

Algorithmlib|Stack

Algorithmlib|Queue

原文鏈接:https://juejin.cn/post/7179162925385383973

欄目分類
最近更新