Skip to content

Instantly share code, notes, and snippets.

@aykutyaman
Created August 28, 2018 04:16
Show Gist options
  • Save aykutyaman/c02e326c6b3efee45e2bc0996e8e44bf to your computer and use it in GitHub Desktop.
Save aykutyaman/c02e326c6b3efee45e2bc0996e8e44bf to your computer and use it in GitHub Desktop.
/**
* Complexity Analysis
* push: O(1)
* pop: Amortized O(1), Worst-case O(n)
* empty: O(1)
* peek: O(1)
*/
function Queue() {
var stack1 = [];
var stack2 = [];
return {
push(val) { // O(1) operation
stack1.push(val);
},
pop(val) {
if (stack2.length === 0) {
while(stack1.length > 0) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
},
// get this front element
peek() {
return stack2[stack2.length - 1] || stack1[0];
},
empty() {
return stack1.length === 0 && stack2.length === 0;
}
};
}
const q = Queue();
q.push(3);
q.push(9);
q.push(12);
console.log(q.peek()); // 3
q.pop();
console.log(q.peek()); // 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment