今天学习了数据结构中的栈结构,我自己的理解是:栈结构是一个受限的,先进后出(frist in last out)的线性数据结构,类似生活中的自助餐盘的堆叠和使用,最后放上去的盘子第一个被使用。
具体实现过程:
class Stack {
// 栈的属性
items = [];
// 栈的相关方法
// 压栈
push(element) {
this.items.push(element);
}
// 从栈中取出元素
pop() {
return this.items.pop();
}
// 返回栈顶元素
shift() {
return this.items[this.items.length - 1];
}
// 判断栈是否为空
isEmpty() {
return this.items.length === 0;
}
// 获取栈中元素个数
size() {
return this.items.length;
}
}
其实也就是用数组的方法实现了一遍栈的功能
实际应用:
function dec2Binary(decNum) {
// 二进制栈
const decNumStack = new Stack();
// 二进制字符
let decStr = "";
// 十进制转二进制
while (decNum > 0) {
decNumStack.push(decNum % 2);
decNum = Math.floor(decNum / 2);
}
while (!decNumStack.isEmpty()) {
decStr += decNumStack.pop();
}
return decStr; // 1100100
}
上图算法是将十进制转二进制的算法并结合了栈的特性,将结果进行了压栈并弹栈最后得到目标二进制,算是栈的一个实际应用。