数据结构TypeScript之栈和队列详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

数据结构TypeScript之栈和队列详解

前端技术獭   2023-02-03 我要评论

栈结构特点

线性表的其中一种,用于存储固定顺序的元素元素增删具有先进后出的特点。

出栈和入栈

在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仓库

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们