栈(stack)又名堆栈,它是一种运算受限的线性表,下面这篇文章主要给大家介绍了关于利用javascript实现栈的数据结构的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
前言
本文主要给大家介绍的是关于javascript实现栈的数据结构的相关内容,分享出来供大家参考学习,话不多少,来一起看看详细的介绍:
堆栈(英语:stack),也可直接称栈,在计算机科学中,是一种特殊的串列形式的数据结构,它的特殊之处在于只能允许在链接串列或阵列的一端(称为堆叠顶端指标,英语:top)进行加入数据(push)和输出数据(pop)的运算。另外栈也可以用一维数组或连结串列的形式来完成。
由于堆叠数据结构只允许在一端进行操作,因而按照后进先出(lifo, last in first out)的原理运作。 – 维基百科
上面是维基百科对栈的解读。下面我们用javascript(es6)代码对栈的数据结构进行实现
实现一个stack类
/**
* stack 类
*/
class stack {
constructor() {
this.data = []; // 对数据初始化
this.top = 0; // 初始化栈顶位置
}
// 入栈方法
push() {
const args = [...arguments];
args.foreach(arg => this.data[this.top++] = arg);
return this.top;
}
// 出栈方法
pop() {
if (this.top === 0) throw new error('the stack is already empty!');
const peek = this.data[--this.top];
this.data = this.data.slice(0, -1);
return peek;
}
// 返回栈顶元素
peek() {
return this.data[this.top - 1];
}
// 返回栈内元素个数
length() {
return this.top;
}
// 清除栈内所有元素
clear() {
this.top = 0;
return this.data = [];
}
// 判断栈是否为空
isempty() {
return this.top === 0;
}
}
// 实例化
const stack = new stack();
stack.push(1);
stack.push(2, 3);
console.log(stack.data); // [1, 2, 3]
console.log(stack.peek()); // 3
console.log(stack.pop()); // 3, now data is [1, 2]
stack.push(3);
console.log(stack.length()); // 3
stack.clear(); // now data is []
用栈的思想将数字转换为二进制和八进制
/**
* 将数字转换为二进制和八进制
*/
const numconvert = (num, base) => {
const stack = new stack();
let converted = '';
while(num > 0) {
stack.push(num % base);
num = math.floor(num / base);
}
while(stack.length() > 0) {
converted += stack.pop();
}
return +converted;
}
console.log(numconvert(10, 2)); // 1010
用栈的思想判断给定字符串或者数字是否是回文
/**
* 判断给定字符串或者数字是否是回文
*/
const ispalindrome = words => {
const stack = new stack();
let wordscopy = '';
words = words.tostring();
array.prototype.foreach.call(words, word => stack.push(word));
while(stack.length() > 0) {
wordscopy += stack.pop();
}
return words === wordscopy;
}
console.log(ispalindrome('1a121a1')); // true
console.log(ispalindrome(2121)); // false
上面就是用javascript对栈的数据结构的实现,有些算法可能欠妥,但是仅仅是为了演示js对栈的实现
以上就是简述如何通过javascript来实现栈的数据结构实例详解的详细内容。