构造模式和数组实现栈

利用js中完善好的数组实现:

//push(element)
//pop(),return and delete it from stack
//peek(), return and no deletion
//size(), return number of elements
//toString(), return stack in the form of string...
//isEmpty(), return true or false
class Stack{
    constructor()
    {
        this.data=[];
    }

    push(element)
    {
        this.data.push(element);
    }

    pop()
    {
        return this.data.pop();
    }
    peek()
    {
        return this.data[this.data.length-1];
    }

    isEmpty(){
        return this.data.length === 0;
    }

    size()
    {
        return this.data.length;
    }

    toString(){
        return this.data.reduce(function(acc,cur){
            return acc+" "+cur.toString();
        },"");
    }
}
const stack=new Stack();
stack.push("maggie");
stack.push([23,45]);
stack.push(new Date().toLocaleString());
console.log(stack.toString());
stack.pop();
stack.pop();
console.log(stack.toString());

因为js的数组本身是对象,并且封装好了pop()和push()两个方法,所以直接利用这两个方法就能立刻实现栈的push()和pop()。

更加底层的实现:

const {log}=console;
//没有考虑数组扩容
function Stack(){
    this.data=[];
    this.top=0;
}
Stack.prototype.push=function(element){
    this.data[this.top++]=element;
}
Stack.prototype.pop=function(){
    return this.data[--this.top];
}
Stack.prototype.peek=function(){
    return this.data[this.top-1];
}
Stack.prototype.size=function(){
    return this.top;
}
Stack.prototype.isEmpty=function(){
    return this.top===0;
}
Stack.prototype.toString=function(){
    let tmp="";
    for(let i=0;i
参考博客:
  • js设计模式之构造函数模式——https://www.cnblogs.com/cangowu/p/5063374.html
  • js实现栈结构——https://www.cnblogs.com/liangsongbai/p/5875681.html

你可能感兴趣的:(构造模式和数组实现栈)