-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQueueS.java
More file actions
62 lines (48 loc) · 1.32 KB
/
Copy pathQueueS.java
File metadata and controls
62 lines (48 loc) · 1.32 KB
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
/*
* Implement Queue using Stack
* details: https://leetcode.com/problems/implement-queue-using-stacks/description/
*
* push(x) - push element x to the back of queue
* pop() - remove the elment from the front of queue
* peek() - get the front element
* empty() - return whether the queue is empty
*/
import java.util.Stack;
public class QueueS<E> {
private Stack<E> stack1;
private Stack<E> stack2;
public QueueS() {
stack1 = new Stack<E>();
stack2 = new Stack<E>();
}
public void push(E x) {
stack1.push(x);
}
public E peek() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.peek();
}
public E pop() {
while (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
public static void main(String[] args) {
QueueS<String> queue = new QueueS<String>();
queue.push("1");
queue.push("2");
System.out.println(queue.peek()); //return 1
queue.pop();
System.out.println(queue.peek()); //return 2
}
}