Skip to content

Instantly share code, notes, and snippets.

@davidkayce
Created July 13, 2021 14:26
Show Gist options
  • Save davidkayce/ba97111dd0da6129fe699eb483ce007c to your computer and use it in GitHub Desktop.
Save davidkayce/ba97111dd0da6129fe699eb483ce007c to your computer and use it in GitHub Desktop.
// Queue using two stacks
function createDoubleStackQueue() {
var that = {};
var pushContainer = [];
var popContainer = [];
function moveElementToPopContainer() {
while (pushContainer.length !==0 ) {
var element = pushContainer.pop();
popContainer.push(element);
}
}
that.push = function(element) {
pushContainer.push(element);
};
that.shift = function() {
if (popContainer.length === 0) {
moveElementToPopContainer();
}
if (popContainer.length === 0) {
return null;
} else {
return popContainer.pop();
}
};
that.front = function() {
if (popContainer.length === 0) {
moveElementToPopContainer();
}
if (popContainer.length === 0) {
return null;
}
return popContainer[popContainer.length - 1];
};
that.length = function() {
return pushContainer.length + popContainer.length;
};
that.isEmpty = function() {
return (pushContainer.length + popContainer.length) === 0;
};
return that;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment