Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Created February 8, 2024 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenarBad/2b7c5fca3e0802a65b4da4fec6d2a9fa to your computer and use it in GitHub Desktop.
Save LenarBad/2b7c5fca3e0802a65b4da4fec6d2a9fa to your computer and use it in GitHub Desktop.
Implement Queue using stacks
class MyQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public MyQueue() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x) {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
s1.push(x);
while (!s2.isEmpty()) {
s1.push(s2.pop());
}
}
public int pop() {
return s1.pop();
}
public int peek() {
return s1.peek();
}
public boolean empty() {
return s1.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment