4.栈

207 阅读1分钟

4 栈

栈是一种特殊形式的列表, 栈只能通过访问栈顶来获取元素,所有的操作也只能针对栈顶元素进行, 位于栈底的元素只能等上面的元素全部出栈之后才能访问, 这也是栈的‘后进先出’特性

对于栈的操作:

  • push 压入栈顶端
  • pop 删除栈顶端
  • peek 获取顶端的元素

4.1 栈的实现

function Stack() {
        this.dataStore = []
        this.pos = 0
    }
    Stack.prototype = {
        push: function (ele) {
            this.dataStore.push(ele)
            this.pos ++
            return this
        },
        pop: function () {
            this.dataStore.pop()
            -- this.pos
            return this
        },
        peek: function () {
            return this.dataStore[this.pos-1]
        }
    }

    let eg = new Stack()
    eg.push('python').push('1').pop().peek()

完整代码

  function Stack() {
        this.dataStore = []
        this.pos = 0
    }
    Stack.prototype = {
        push: function (ele) {
            this.dataStore.push(ele)
            this.pos ++
            return this
        },
        pop: function () {
            this.dataStore.pop()
            -- this.pos
            return this
        },
        peek: function () {
            return this.dataStore[this.pos-1]
        },
        length: function() {
            return this.pos
        },
        clear: function() {
            this.dataStore = []
        }
    }

    let eg = new Stack()  
    eg.push('python').push('1').pop().peek()

    let str1 = '{{([])}}'
    let str2 = '}[]}'
    let str3 = '{(])'
    let str4 = '{())}'
    function main(str) {
        let stack = new Stack()
        for(let i = 0; i< str.split('').length; i++) {
            let item = str.split('')[i]
            // console.log(stack.dataStore, item )
            if(item == '{' || item == '[' || item == '(') {
                stack.push(item)
            } else if(stack.peek() == '{' && item == '}') {
                stack.pop()
            }
            else if(stack.peek() == '[' && item == ']') {
                stack.pop()
            }
            else if(stack.peek() == '(' && item == ')') {
                stack.pop()
            } else {
                return false
            }
        }
        return true
    }