js 实现栈结构

    //实现栈结构基本操作

    function Stack() {

        this.items = [];

        //1. push(element) 入栈操作

        Stack.prototype.push = function (element) {

            this.items.push(element);

        }



        //2. pop() 出栈操作 

        Stack.prototype.pop = function () {

           return this.items.pop();

        }



        //3. isEmpty() 是否为空栈  

        Stack.prototype.isEmpty = function () {

            return this.items.length === 0;

        }



        //4. peek() 返回栈顶元素 不对栈做修改

        Stack.prototype.peek = function () {

            return this.items[this.items.length-1];

        }

        //5. size() 返回栈的数量

       Stack.prototype.size = function () {

           return this.items.length;

       }

        //6. toString() 方法

        Stack.prototype.toString = function () {

            let result =  '';

            for(let i = 0; i < this.items.length; i++) {

                let sign = i === this.items.length-1?'':',';

                result += this.items[i] + sign 



            }

            return result;

        }

    }   

    let s = new Stack();
    

你可能感兴趣的:(js 实现栈结构)