Skip to content

Instantly share code, notes, and snippets.

@cixuuz
Created October 11, 2017 18:50
Show Gist options
  • Select an option

  • Save cixuuz/b9e5e057864b93c998b86b8af96f41d0 to your computer and use it in GitHub Desktop.

Select an option

Save cixuuz/b9e5e057864b93c998b86b8af96f41d0 to your computer and use it in GitHub Desktop.
[232. Implement Queue using Stacks] #leetcode
class MyQueue {
private Deque<Integer> deque1;
private Deque<Integer> deque2;
private int count;
/** Initialize your data structure here. */
public MyQueue() {
deque1 = new LinkedList<Integer>();
deque2 = new LinkedList<Integer>();
count = 0;
}
/** Push element x to the back of queue. */
public void push(int x) {
deque1.addLast(x);
count++;
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
changeDeque();
count--;
return deque2.removeLast();
}
/** Get the front element. */
public int peek() {
changeDeque();
return deque2.peekLast();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return count == 0;
}
private void changeDeque() {
if (deque2.size() == 0) {
int n = deque1.size();
for (int i = 0; i < n; i++) {
deque2.addLast(deque1.removeLast());
}
}
}
}
/**
* 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