JavaScript 的数据结构和算法 - 栈代码篇
JavaScript 版本的栈的实现
这篇文章主要是栈这种数据解构的 JavaScript 代码实现,更多文字相关介绍,请 移步
构造函数
constructor() {
/**
* @type {*[]}
*/
this.data = []
/**
* @type {number}
*/
this.count = 0
}
主要方法实现
入栈操作
/**
* Add new element to the top.
* @param item
*/
push(item) {
this.data[this.count] = item
this.count++
}
/**
* Building Stack of array by array
* @param {Array} array
*/
build(array) {
this.count = array.length
this.data = array
}
出栈操作
/**
* The most top element of the stack is removed from the stack and returned.
* @returns {null|T}
*/
pop() {
if (this.count === 0) {
return null
}
const element = this.data.pop()
this.count--
return element
}
辅助方法实现
/**
* Get stack size 获取栈的大小
* @returns {number}
*/
get size () {
return this.count
}
源码地址 https://github.com/MasterShu/JavaScript-Da...
本作品采用《CC 协议》,转载必须注明作者和本文链接