-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplementQueueUsingStacks.java
More file actions
53 lines (38 loc) · 996 Bytes
/
ImplementQueueUsingStacks.java
File metadata and controls
53 lines (38 loc) · 996 Bytes
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
package java_exercise;
import java.util.Stack;
public class ImplementQueueUsingStacks {
/*
* mplement the following operations of a queue using stacks.
* push(x) -- Push element x to the back of queue.
* pop() -- Removes the element from in front of queue.
* peek() -- Get the front element.
* empty() -- Return whether the queue is empty.
*/
Stack<Integer> converter = new Stack<Integer>();
Stack<Integer> s = new Stack<Integer>();
public void push(int x) {
if (s.empty()) {
s.push(x);
} else {
while(!s.empty()) {
converter.push(s.pop());
}
converter.push(x);
while(!converter.empty()) {
s.push(converter.pop());
}
}
}
// Removes the element from in front of queue.
public void pop() {
s.pop();
}
// Get the front element.
public int peek() {
return s.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return (s.empty());
}
}