Skip to content

Commit f75fbd8

Browse files
authored
Add files via upload
1 parent 5b70301 commit f75fbd8

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Queue/queueUsingTwoStacks.java

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
Queue using Two Stacks
3+
4+
A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed.
5+
6+
A basic queue has the following operations:
7+
8+
Enqueue: add a new element to the end of the queue.
9+
Dequeue: remove the element from the front of the queue and return it.
10+
In this challenge, you must first implement a queue using two stacks. Then process queries, where each query is one of the following types:
11+
12+
1 x: Enqueue element into the end of the queue.
13+
2: Dequeue the element at the front of the queue.
14+
3: Print the element at the front of the queue.
15+
*/
16+
17+
import java.io.*;
18+
import java.util.*;
19+
import java.text.*;
20+
import java.math.*;
21+
import java.util.regex.*;
22+
23+
public class queueUsingTwoStacks {
24+
25+
public static Stack<Integer> s1 = new Stack<>();
26+
public static Stack<Integer> s2 = new Stack<>();
27+
28+
public static void enqueue(int x)
29+
{
30+
s1.push(x);
31+
}
32+
33+
public static void dequeue()
34+
{
35+
if(s2.empty())
36+
{
37+
while(!s1.empty())
38+
{
39+
s2.push(s1.peek());
40+
s1.pop();
41+
}
42+
}
43+
s2.pop();
44+
}
45+
46+
public static void print()
47+
{
48+
if(s2.empty())
49+
{
50+
while(!s1.empty())
51+
{
52+
s2.push(s1.peek());
53+
s1.pop();
54+
}
55+
}
56+
System.out.println(s2.peek());
57+
}
58+
59+
public static void main(String[] args) {
60+
61+
Scanner in = new Scanner(System.in);
62+
63+
int n = in.nextInt();
64+
int i,q,x;
65+
66+
for(i=0;i<n;i++)
67+
{
68+
q = in.nextInt();
69+
70+
switch(q)
71+
{
72+
case 1:
73+
x = in.nextInt();
74+
enqueue(x);
75+
break;
76+
case 2:
77+
dequeue();
78+
break;
79+
case 3:
80+
print();
81+
break;
82+
}
83+
}
84+
85+
}
86+
}

0 commit comments

Comments
 (0)