Skip to content

Commit aef99c0

Browse files
authored
Create StackusingQueue.java
1 parent d4f6b3d commit aef99c0

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

StackusingQueue.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/* Java Program to implement a stack using
2+
two queue */
3+
import java.util.*;
4+
5+
class GfG {
6+
7+
static class Stack {
8+
// Two inbuilt queues
9+
static Queue<Integer> q1 = new LinkedList<Integer>();
10+
static Queue<Integer> q2 = new LinkedList<Integer>();
11+
12+
// To maintain current number of
13+
// elements
14+
static int curr_size;
15+
16+
Stack()
17+
{
18+
curr_size = 0;
19+
}
20+
21+
static void push(int x)
22+
{
23+
curr_size++;
24+
25+
// Push x first in empty q2
26+
q2.add(x);
27+
28+
// Push all the remaining
29+
// elements in q1 to q2.
30+
while (!q1.isEmpty()) {
31+
q2.add(q1.peek());
32+
q1.remove();
33+
}
34+
35+
// swap the names of two queues
36+
Queue<Integer> q = q1;
37+
q1 = q2;
38+
q2 = q;
39+
}
40+
41+
static void pop()
42+
{
43+
44+
// if no elements are there in q1
45+
if (q1.isEmpty())
46+
return;
47+
q1.remove();
48+
curr_size--;
49+
}
50+
51+
static int top()
52+
{
53+
if (q1.isEmpty())
54+
return -1;
55+
return q1.peek();
56+
}
57+
58+
static int size()
59+
{
60+
return curr_size;
61+
}
62+
}
63+
64+
// driver code
65+
public static void main(String[] args)
66+
{
67+
Stack s = new Stack();
68+
s.push(1);
69+
s.push(2);
70+
s.push(3);
71+
72+
System.out.println("current size: " + s.size());
73+
System.out.println(s.top());
74+
s.pop();
75+
System.out.println(s.top());
76+
s.pop();
77+
System.out.println(s.top());
78+
79+
System.out.println("current size: " + s.size());
80+
}
81+
}
82+
// This code is contributed by Prerna

0 commit comments

Comments
 (0)