-
Notifications
You must be signed in to change notification settings - Fork 5
/
Queue.java
104 lines (86 loc) · 1.79 KB
/
Queue.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
import java.util.*;
// define queue class
class Queue
{
int arr[], front, rear, cap, n1;
// Queue constructor
Queue(int n)
{
arr = new int[n];
cap = n;
front = 0;
rear = -1;
n = 0;
}
// dequeue function for removing the front element
public void dequeue()
{
// check for queue underflow
if (isEmpty())
{
System.out.println("No items in the queue,cannot delete");
System.exit(1);
}
System.out.println("Deleting " + arr[front]);
front = (front + 1) % cap;
n1--;
}
// enqueue function for adding an item to the rear
public void enqueue(int val)
{
// check for queue overflow
if (isFull())
{
System.out.println("OverFlow!!Cannot add more values");
System.exit(1);
}
System.out.println("Adding " + val);
rear = (rear + 1) % cap;
arr[rear] = val;
n1++;
}
// peek function to return front element of the queue
public int peek()
{
if (isEmpty())
{
System.out.println("Queue empty!!Cannot delete");
System.exit(1);
}
return arr[front];
}
// returns the size of the queue
public int size()
{
return n1;
}
// to check if the queue is empty or not
public Boolean isEmpty()
{
return (size() == 0);
}
// to check if the queue is full or not
public Boolean isFull()
{
return (size() == cap);
}
// Queue implementation in java
public static void main (String[] args)
{
// create a queue of capacity 5
Queue q = new Queue(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
System.out.println("Front element is: " + q.peek());
q.dequeue();
System.out.println("Front element is: " + q.peek());
System.out.println("Queue size is " + q.size());
q.dequeue();
q.dequeue();
if (q.isEmpty())
System.out.println("Queue Is Empty");
else
System.out.println("Queue Is Not Empty");
}
}