forked from pandeyprem/DSA-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplementingQueue.java
124 lines (100 loc) · 2.84 KB
/
ImplementingQueue.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
Implementing the Concepts of Queue using java.
Queue is a Linear Data Structure which follows FIFO(First In First Out) concept.
Inserting the element -> Enqueue;
Removing the Element -> Dequeue
*/
package Queue;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ImplementingQueue {
private Node front;
private Node rear;
private int length;
private static class Node{
private int data;
private Node next;
public Node(int data){
this.data = data;
}
}
public ImplementingQueue(){
this.front = null;
this.rear = null;
this.length = 0;
}
public boolean isEmpty(){
return length == 0;
}
public int getLength(){
return length;
}
// Method to insert data into the Queue
public void Enqueue(int data){
Node temp = new Node(data);
if(isEmpty()){
front = temp;
}else{
rear.next = temp;
}
rear = temp;
length++;
}
// Method to Remove data from the Queue
public int Dequeue(){
if(isEmpty()){
throw new NoSuchElementException();
}
int val = front.data;
front = front.next;
if(front == null){
rear = null;
}
length--;
return val;
}
// Method to print the Element of the Queue
public void print(){
if(isEmpty()){
return;
}
Node current = front;
while(current != null){
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.print("Null");
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ImplementingQueue queue = new ImplementingQueue();
while(true){
System.out.println("Please Enter your choice : \n" +
"Press 0 to Exit \n" +
"Press 1 to Insert Data \n" +
"Press 2 to Remove Data \n" +
"Press 3 to print Data \n");
int choice = sc.nextInt();
switch (choice){
case 0 -> {
System.exit(0);
}
case 1 -> {
System.out.println("Enter the Data :");
int data = sc.nextInt();
queue.Enqueue(data);
}
case 2 -> {
System.out.println("Dequeued Element is " + queue.Dequeue());
}
case 3 -> {
queue.print();
}
default -> {
System.out.println("Wrong Input!!!");
}
}
}
}
}