Created
February 8, 2024 18:25
-
-
Save LenarBad/ad2a5e0cc42b3d721936cd9db705e083 to your computer and use it in GitHub Desktop.
Implement Stack using Queues
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 MyStack { | |
private Queue<Integer> q; | |
public MyStack() { | |
this.q = new LinkedList(); | |
} | |
public void push(int x) { | |
q.add(x); | |
for (int i = 0; i < q.size() - 1; i++) { | |
q.add(q.poll()); | |
} | |
} | |
public int pop() { | |
return q.poll(); | |
} | |
public int top() { | |
return q.peek(); | |
} | |
public boolean empty() { | |
return q.isEmpty(); | |
} | |
} | |
/** | |
* Your MyStack object will be instantiated and called as such: | |
* MyStack obj = new MyStack(); | |
* obj.push(x); | |
* int param_2 = obj.pop(); | |
* int param_3 = obj.top(); | |
* boolean param_4 = obj.empty(); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment