4 the stack

A stack is a special form of list in which elements can only be accessed by accessing the top of the stack. All operations can only be performed on the top of the stack. The elements at the bottom of the stack can only be accessed after all the upper elements are removed from the stack, which is also the ‘last in, first out’ feature of the stack

For stack operations:

  • Push onto the top of the stack
  • Pop removes top of stack
  • Peek gets the top element

4.1 Implementation of stack

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()
Copy the code

The complete code

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 }Copy the code