My LeetCode Diary - Day10 Stack&Queue
232. Implement Queue using Stacks
Link
class MyQueue {
Stack<Integer> inStack;
Stack<Integer> outStack;
public MyQueue() {
this.inStack = new Stack<>();
this.outStack = new Stack<>();
}
public void push(int x) {
while(!outStack.isEmpty()){
inStack.push(outStack.pop());
}
inStack.push(x);
while(!inStack.isEmpty()){
outStack.push(inStack.pop());
}
}
public int pop() {
if(outStack.isEmpty()){
return -1;
}
return outStack.pop();
}
public int peek() {
if(outStack.isEmpty()){
return -1;
}
return outStack.peek();
}
public boolean empty() {
return outStack.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();
*/
225. Implement Stack using Queues
Link
class MyStack {
Deque<Integer> que1;
public MyStack() {
que1 = new ArrayDeque<>();
}
public void push(int x) {
que1.addLast(x);
}
public int pop() {
int size = que1.size();
size--;
while (size-- > 0){
que1.addLast(que1.peekFirst());
que1.pollFirst();
}
int res = que1.pollFirst();
return res;
}
public int top() {
return que1.peekLast();
}
public boolean empty() {
return que1.isEmpty();
}
}