InterviewMap / CS-Interview-Knowledge-Map

Build the best interview map. The current content includes JS, network, browser related, performance optimization, security, framework, Git, data structure, algorithm, etc.
https://yuchengkai.cn/docs/frontend/
18.3k stars 2.57k forks source link

栈结构的实现 #163

Closed yanyue404 closed 6 years ago

yanyue404 commented 6 years ago

提问

这里是否应该使用unshift入栈,shift出栈更好一些?

 class Stack {
      constructor() {
        this.stack = []
      }
      push(item) {
        this.stack.unshift(item);
        console.log(item + "------- , 入栈操作");

      }
      pop() {
        var current = this.stack.shift();
        console.log(current + "------- , 出栈操作");
        return current;
      }
      peek() {
        return this.stack[this.getCount() - 1]
      }
      getCount() {
        return this.stack.length
      }
      isEmpty() {
        return this.getCount() === 0
      }
    }

    var arr = new Stack();
    var nowStackLog = function () {
      var state = arr.isEmpty() ? "空栈" : arr.stack;
      console.log(state + "------- , 当前栈内存");
    }

    nowStackLog();
    arr.push(1);
    arr.push(2);
    arr.push(3);
    nowStackLog();

    arr.pop();
    arr.pop();
    arr.pop();
    nowStackLog();
KieSun commented 6 years ago

这两个操作的空间复杂度有考虑过么?