網(wǎng)站首頁 編程語言 正文
棧結(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
相關(guān)推薦
- 2022-05-25 SpringCloud和微服務之間的關(guān)系
- 2022-09-15 python實現(xiàn)簡單的計算器功能_python
- 2021-11-26 linux服務器磁盤空間擴充方法_Linux
- 2022-06-24 PyTorch中permute的基本用法示例_python
- 2022-11-13 C語言在輸入輸出時遇到的常見問題總結(jié)_C 語言
- 2022-06-25 python數(shù)據(jù)可視化之日期折線圖畫法_python
- 2022-04-14 error: failed to push some refs to ‘http://git.tex
- 2022-10-21 Golang驗證器之validator是使用詳解_Golang
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支