-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathImplementQueueUsingStacks.java
75 lines (62 loc) · 1.76 KB
/
ImplementQueueUsingStacks.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package problems.leetcode;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* https://leetcode.com/problems/implement-queue-using-stacks/
*/
public class ImplementQueueUsingStacks {
private static class MyQueue {
private Deque<Integer> stack1 = new ArrayDeque<>();
private Deque<Integer> stack2 = new ArrayDeque<>();
/**
* Initialize your data structure here.
*/
public MyQueue() {
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
stack1.addLast(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
if (stack2.size() == 0) {
while (stack1.size() > 0) {
stack2.addLast(stack1.removeLast());
}
}
return stack2.removeLast();
}
/**
* Get the front element.
*/
public int peek() {
if (stack2.size() == 0) {
while (stack1.size() > 0) {
stack2.addLast(stack1.removeLast());
}
}
return stack2.peekLast();
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}
public static void main(String[] args) {
MyQueue queue = new MyQueue();
queue.push(5);
queue.push(6);
queue.push(7);
System.out.println(queue.pop());
queue.push(8);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}