ES5实现
实现1:方法添加到类上
//声明这个类的构造函数
function Stack(items){
//用来保存栈里的元素
this.items = items || [];
//向栈顶添加元素
this.push = function(element){
//push():向数组的末尾添加一个或更多元素,返回新的长度
this.items.push(element);
}
//移除栈顶的元素
this.pop = function(){
//pop():删除数组的最后一个元素并返回删除数组的元素
return this.items.pop();
}
//返回栈顶的元素
this.peek = function(){
return this.items[this.items.length-1];
}
//判断栈是否为空
this.isEmpty = function(){
return this.items.length === 0;
}
//返回栈里元素的个数
this.size = function(){
return this.items.length;
}
//移除栈里所有元素
this.clear = function(){
// this.items.splice(0, this.items.length);
this.items = [];
}
this.print = function(){
console.log(this.items.toString());
}
}
实现2:方法添加到原型上(说是节省内存,我还不太懂)
function Stack(items){
this.items = items || [];
Stack.prototype.push = function(element) {
this.items.push(element);
}
Stack.prototype.pop = function() {
return this.items.pop();
}
Stack.prototype.peek = function() {
return this.items[this.items.length - 1];
}
Stack.prototype.isEmpty = function() {
return this.items.length === 0;
}
Stack.prototype.size = function() {
return this.items.length;
}
Stack.prototype.print = function() {
console.log(this.items.toString());
}
Stack.prototype.clear = function() {
this.items = [];
}
}
一些栈应用案例:
数据结构使用上面两种都可
1. 十进制转二进制
function dec2bin(decNumber){
let stack = new Stack();
while(decNumber > 0){
stack.push(decNumber % 2);
decNumber = Math.floor(decNumber / 2);
}
let binaryStr = '';
while(!stack.isEmpty()){
binaryStr += stack.pop();
}
return binaryStr;
}