Created
February 8, 2024 18:22
-
-
Save LenarBad/2b7c5fca3e0802a65b4da4fec6d2a9fa to your computer and use it in GitHub Desktop.
Implement Queue using stacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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