美文网首页
构造模式和数组实现栈

构造模式和数组实现栈

作者: meteornnnight | 来源:发表于2019-06-02 12:33 被阅读0次

    利用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<this.top;i++){
            tmp=tmp+this.data[i];
        }
        return tmp;
    }
    const s=new Stack();
    s.push(1);
    s.push(0);
    s.push(2);
    s.push(3);
    s.push(4);
    log(s.toString());
    s.pop();
    s.pop();
    s.push(5);
    log(s.toString());
    
    
    参考博客:

    相关文章

      网友评论

          本文标题:构造模式和数组实现栈

          本文链接:https://www.haomeiwen.com/subject/mahxxctx.html