232. Implement Queue using Stacks

202410271042
tags: #stack #queue

var MyQueue = function() {
	this.stackIn = [];
	this.stackOut = [];
};

MyQueue.prototype.push = function(x) {
	this.stackIn.push(x);
};

MyQueue.prototype.pop = function() {
	if (this.stackOut.length > 0) {
		return this.stackOut.pop();
	}
	while (this.stackIn.length > 0) {
		this.stackOut.push(this.stackIn.pop());
	}
	return this.stackOut.pop();
};

MyQueue.prototype.peek = function() {
	const peekElement = this.pop();
	this.stackOut.push(peekElement);
	return peekElement;
};

MyQueue.prototype.empty = function() {
	return this.stackIn.length === 0 && this.stackOut.length === 0;
};

Reference

https://leetcode.com/problems/implement-queue-using-stacks/