@lexstile

Как правильно решить задачу на js?

function Stack() {
    // TODO
    return {
        push() {},
        pop() {}
    };
}

const stack = new Stack();

stack.push(123);
stack.push(456);
stack.push(789);

console.log(stack.pop()); // 789
console.log(stack.pop()); // 456
console.log(stack.pop()); // 123

push() - должен добавлять данные в Stack;
pop() - должен извлекать данные из стека (последние добавленные)
  • Вопрос задан
  • 155 просмотров
Решения вопроса 1
@bogomazov_vadim
Реализация стека на js гуглится за полминуты.
Остается немного подогнать.

function Stack() {
    this._size = 0;
    this._storage = {};
}
 
Stack.prototype.push = function(data) {
    var size = ++this._size;
    this._storage[size] = data;
};
 
Stack.prototype.pop = function() {
    var size = this._size,
        deletedData;
 
    if (size) {
        deletedData = this._storage[size];
 
        delete this._storage[size];
        this._size--;
 
        return deletedData;
    }
};

class Stack {
  constructor() {
    this.stack = []
  }
  
  // Inserts the element into the top of the stack
  push(element) {
    this.stack.push(element)
  }
  
  // Removes the element from the top of the stack and return that element
  pop() {
    if (this.isEmpty()) return 'Stack is empty!'
    return this.stack.pop()
  }
  
  // Return which element is on top of the stack
  peek() {
    if (this.isEmpty()) return 'Stack is empty'
    return this.stack[this.stack.length - 1]
  }
  
  // helper method
  isEmpty() {
    return !this.stack.length
  }
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы