Skip to content

Commit 6167930

Browse files
authored
Create Implement Queue using Linked List.java
1 parent a855c44 commit 6167930

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
//{ Driver Code Starts
2+
import java.util.*;
3+
class QueueNode
4+
{
5+
int data;
6+
QueueNode next;
7+
QueueNode(int a)
8+
{
9+
data = a;
10+
next = null;
11+
}
12+
}
13+
14+
class GfG {
15+
public static void main(String args[])
16+
{
17+
Scanner sc = new Scanner(System.in);
18+
int t=sc.nextInt();
19+
while(t>0)
20+
{
21+
MyQueue obj = new MyQueue();
22+
int Q = sc.nextInt();
23+
while(Q>0)
24+
{
25+
int QueryType = 0;
26+
QueryType = sc.nextInt();
27+
if(QueryType == 1)
28+
{
29+
int a = sc.nextInt();
30+
31+
obj.push(a);
32+
33+
}else if(QueryType == 2)
34+
{
35+
System.out.print(obj.pop()+" ");
36+
}
37+
Q--;
38+
}
39+
System.out.println("");
40+
t--;
41+
}
42+
}
43+
}
44+
45+
46+
47+
48+
49+
// } Driver Code Ends
50+
51+
52+
/*The structure of the node of the queue is
53+
class QueueNode
54+
{
55+
int data;
56+
QueueNode next;
57+
QueueNode(int a)
58+
{
59+
data = a;
60+
next = null;
61+
}
62+
}*/
63+
64+
class MyQueue
65+
{
66+
QueueNode front, rear;
67+
68+
//Function to push an element into the queue.
69+
void push(int a)
70+
{
71+
// Your code here
72+
QueueNode newnode = new QueueNode(a);
73+
if(rear == null){
74+
front = newnode;
75+
rear = newnode;
76+
} else {
77+
rear.next = newnode;
78+
rear = newnode;
79+
}
80+
81+
82+
}
83+
84+
//Function to pop front element from the queue.
85+
int pop()
86+
{
87+
// Your code here
88+
89+
int temp = 0;
90+
91+
if(front == null){
92+
return -1;
93+
} else {
94+
temp = front.data;
95+
front = front.next;
96+
if(front == null){
97+
rear = null;
98+
}
99+
}
100+
return temp;
101+
}
102+
}
103+
104+
105+
106+

0 commit comments

Comments
 (0)