-
Notifications
You must be signed in to change notification settings - Fork 17
/
StackUsingQueue.java
56 lines (51 loc) · 1.14 KB
/
StackUsingQueue.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
package SummerTrainingGFG.Queue;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* @author Vishal Singh
*/
class Stack{
Queue<Integer> q1 = new ArrayDeque<>();
Queue<Integer> q2 = new ArrayDeque<>();
int top(){
if (q1.isEmpty()){
return -1;
}
return q1.peek();
}
int size(){
return q1.size();
}
int pop(){
if (q1.isEmpty()){
return -1;
}
return q1.poll();
}
void push(int data){
while(!q1.isEmpty()){
q2.offer(q1.peek());
q1.poll();
}
q1.offer(data);
while (!q2.isEmpty()){
q1.offer(q2.peek());
q2.poll();
}
}
}
public class StackUsingQueue {
public static void main(String[] args) {
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
System.out.println("current size: " + s.size());
System.out.println(s.top());
s.pop();
System.out.println(s.top());
s.pop();
System.out.println(s.top());
System.out.println("current size: " + s.size());
}
}