-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_Stack_using_Queues_225.java
More file actions
45 lines (38 loc) · 1.1 KB
/
Copy pathImplement_Stack_using_Queues_225.java
File metadata and controls
45 lines (38 loc) · 1.1 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
class MyStack {
// Push element x onto stack.
Queue<Integer> queue = new LinkedList<Integer>() ;
public void push(int x) {
queue.offer(x) ;
}
// Removes the element on top of the stack.
public void pop() {
Queue<Integer> tempQ = new LinkedList<Integer>() ;
while(!queue.isEmpty()) {
Integer i = queue.remove() ;
if (!queue.isEmpty())tempQ.offer(i) ;
}
while(!tempQ.isEmpty()) {
Integer i = tempQ.remove() ;
queue.offer(i) ;
}
}
// Get the top element.
public int top() {
int ans = -1 ;
Queue<Integer> tempQ = new LinkedList<Integer>() ;
while(!queue.isEmpty()) {
Integer i = queue.remove() ;
tempQ.offer(i) ;
if (queue.isEmpty()) ans = i ;
}
while(!tempQ.isEmpty()) {
Integer i = tempQ.remove() ;
queue.offer(i) ;
}
return ans ;
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty() ;
}
}