Configuration mode and stack arrays to achieve

Js sound good use in an array of implementation:

//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 because the array itself is an object and two packaging methods well pop () and push (), so the direct use of these two methods can be implemented immediately stack push () and pop ().

More underlying implementation:

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());

Reference blog:

Guess you like

Origin blog.csdn.net/weixin_33749131/article/details/90872214