栈结构
栈,遵循后进先出(LIFO:last in fist out)的规则,这一规则与数组的的push、pop方法很像。所以我们可以利用数组中的这两个方法来实现栈结构.
基于数组实现栈结构
function Stack(){
this.list = [];
// 进栈
Stack.prototype.push = function(item){
this.list.push(item);
}
// 出栈
Stack.prototype.pop = function(){
return this.list.pop();
}
// 查栈顶元素
Stack.prototype.peek = function(){
return this.list[this.list.length - 1];
}
// 栈是否为空
Stack.prototype.isEmpty = function(){
return !this.list.length;
}
// 清空栈
Stack.prototype.clear = function(){
this.list = [];
}
// 查栈的大小
Stack.prototype.size = function(){
return this.list.length;
}
}
测试栈结构
基于数组的栈结构的弊端:
我们知道,数组是一个有序的集合,
那么在数据量较小的时候,这种基于数组封装的栈结构貌似没有太大的问题;
但是数量比较大时,那么数组便会占用一个很大的连续空间,以保证它的有序性,这时,
使用数组来封装栈结构,便不太合理了。
下面是基于javascript的对象,来封装栈结构,这可以从某种程度上,可以更大化利用内存空间。
function StackFromObj(){
this.list = {};
this.count = 0;
// 基于 count 作为list的key,进行模拟栈结构,"进栈"
StackFromObj.prototype.push = function (item){
this.list[this.count] = item;
this.count++;
}
// "出栈"
StackFromObj.prototype.pop = function (){
if(this.isEmpty()) return undefined;
this.count--;
let popData = this.list[this.count];
delete this.list[this.count];
return popData;
}
// 是否为空
StackFromObj.prototype.isEmpty = function (){
return !this.count;
}
// 返回栈顶元素
StackFromObj.prototype.peek = function (){
if(this.isEmpty()) return undefined;
return this.list[this.count - 1];
}
// 清空栈
StackFromObj.prototype.clear = function (){
this.list = {};
this.count = 0;
}
// 返回栈元素个数
StackFromObj.prototype.size = function (){
return this.count;
}
// toString方法
StackFromObj.prototype.toString = function (){
if(this.isEmpty()) return "";
let str = "";
Object.keys(this.list).forEach(item => {
str += this.list[item] += " ";
});
return str;
}
}
应用
栈的应用很广泛,这里举一个算法练习中常见的例子:进制转换
parseBaseSystem(130); // 10000010
parseBaseSystem(130, 10); // 130
parseBaseSystem(130, 8); // 202
parseBaseSystem(130, 16); // 82
function parseBaseSystem(num, bin = 2){
let stack = new StackFromObj();
let res = num;
let rem;
let reslute = "";
while(res > 0){
rem = Math.floor(res % bin);
res = Math.floor(res / bin);
stack.push(rem);
}
while(!stack.isEmpty()){
reslute += stack.pop();
}
console.log(reslute)
return reslute
}
这些就是栈的基本知识了,下一章节,分享队列的数据结构