数据结构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数据结构栈和队列的资料请关注脚本之家其它相关文章!
相关文章
FastAdmin表单验证data-rule插件—Nice-validator的使用方法
FastAdmin的表单验证data-rule非常方便,也很炫酷,采用的Nice-validator是一款非常强大的表单验证插件,通过简单在元素上配置规则,即可达到验证的效果,怎么使用Nice-validator插件呢2023-09-09TypeScript 基础数据结构哈希表 HashTable教程
这篇文章主要为大家介绍了TypeScript 基础数据结构哈希表 HashTable教程详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-02-02
最新评论