Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Created March 6, 2017 17:56
Show Gist options
  • Save vitkarpov/aadb11e5cd5e51c08dd59ef8c4d4a81f to your computer and use it in GitHub Desktop.
Save vitkarpov/aadb11e5cd5e51c08dd59ef8c4d4a81f to your computer and use it in GitHub Desktop.
"Cracking the coding interview", Stacks and Queues, 3.5
/**
* Реализует очередь с помощью двух стеков.
*
* @example
* const q = new MyQueue();
* q.add(10);
* q.add(12);
* q.add(15);
* q.add(17);
* // 10
* q.remove();
* // 12
* q.remove();
*/
class MyQueue {
constructor() {
// здесь храним добавленные элементы
this._s1 = [];
// сюда копируем все из первого стека при попытке забрать элемент,
// в таком случае — этот стек будет содержать элементы в обратном порядке
this._s2 = [];
}
add(value) {
this._s1.push(value);
}
remove() {
this._shift();
return this._s2.pop();
}
peek() {
this._shift();
return this._s2[this._s2.length - 1];
}
/**
* Заполняет второй стек
* элементами из первого в обратном порядке
*/
_shift() {
if (this._s2.length > 0) {
return;
}
while (this._s1.length > 0) {
this._s2.push(this._s1.pop());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment