基本的数据结构 - 栈
栈的概念特点
- 有序集合;
- 遵循后进先出(LIFO)原则;
- 新元素靠近栈顶,旧元素靠近栈底。
栈常用的方法
- push(element): 添加新元素到栈顶
- pop(): 移除栈顶元素,同时返回被移除的元素
- peek(): 只查看栈顶元素,不修改栈的元素
- isEmpty(): 判空,栈为空返回true,反之false
- clear(): 清空栈
- size(): 返回栈的大小
- toString(): toString方法
栈的实现
基于数组实现栈的常用方法
function Stack(){
// 栈中的属性
this.items = [];
// 栈相关的操作
// 1. 压栈
Stack.prototype.push = function (element){
this.items.push(element);
}
// 移除栈顶元素,同时返回被移除的元素
Stack.prototype.pop = function (){
return this.items.pop();
}
// 3. 查看栈顶元素
Stack.prototype.peek = function (){
return this.items[this.items.length -1];
}
// 4. 判断栈是否为空
Stack.prototype.isEmpty = function (){
return this.items.length == 0;
}
// 5. 清空栈
Stack.prototype.clear = function (){
this.items = [];
}
// 6. 获取栈的大小
Stack.prototype.size = function (){
return this.items.length;
}
// 7. toString方法
Stack.prototype.toString = function (){
var resultString = "";
for(var i = 0;i < this.items.length;i++){
resultString += this.items[i] + "";
}
return resultString;
}
}
let stack = new Stack();
stack.push(10);
stack.push(13);
stack.push(12);
stack.push(15);
console.log(stack);
栈的应用
将十进制转换为指定进制
import {Stack} from "./CreateStack.js";
function dec2bin(num,baseSystem){
// 1. 定义栈对象
const stack = new Stack();
// 2. 循环操作
while(num > 0){
//2.1 将余数存储到栈中
stack.push(num % baseSystem);
// 2.2 将整除的结果,作为下一次运行的数字
num = Math.floor(num /baseSystem);
}
// 3. 从从栈中取出0和1
let binaryString = "";
while(!stack.isEmpty()){
binaryString+= stack.pop();
}
return binaryString;
}
console.log(dec2bin(10,2));