Created
October 11, 2017 18:50
-
-
Save cixuuz/b9e5e057864b93c998b86b8af96f41d0 to your computer and use it in GitHub Desktop.
[232. Implement Queue using Stacks] #leetcode
This file contains hidden or 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 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