-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFixedArraySimpleQueue.java
155 lines (145 loc) · 3.49 KB
/
FixedArraySimpleQueue.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
abstract class FixedArraySimpleQueue
{
private static class FixedArrayQueue
{
private int front;
private int rear;
private int[] que;
/**
* default constructor
*/
public FixedArrayQueue()
{
this(5);
}
/**
* default constructor
* @param size
*/
public FixedArrayQueue(int size)
{
que = new int[size];
front=-1;
rear=-1;
}
/**
* This method will add an element to the queue
* @param val for value to enqueue
* @throws Exception
* @return void
*/
public void enqueue(int val) throws Exception
{
if(front==-1 && rear==-1)
{
front++;
}
rear++;
if(rear==que.length)
{
throw new Exception("FullQueueException");
}
que[rear]=val;
}
/**
* This method will remove an element from the queue
* @return int dequeued value
* @throws Exception
*/
public int dequeue() throws Exception
{
if(front==-1 || rear==-1)
{
throw new Exception("EmptyQueueException");
}
int temp = que[front];
//shifting left
int i=0;
for(i=0;i<que.length-1;i++)
{
que[i]=que[i+1];
}
que[i]=0;
rear--;
return temp;
}
/**
* It will return the front value from the queue
* @return int front value
*/
public int front()
{
if(isEmpty())
{
return -1;
}
return que[front];
}
/**
* It will return the size of the Queue
* @return int size of the Queue
*/
public int size()
{
return rear-front+1;
}
/**
* Tells whether the Queue is empty or not
* @return boolean
*/
public boolean isEmpty()
{
if(front==-1 || rear==-1)
{
return true;
}
return false;
}
/**
* It will print the queue array
* @param void
* @return void
**/
public void printCheck()
{
for(int i=0;i<que.length;i++)
{
System.out.print(que[i]+" ");
}
System.out.println();
}
}
public static void main(String[] args)
{
try
{
FixedArrayQueue Q = new FixedArrayQueue();
System.out.println(Q.isEmpty());
Q.enqueue(1);
Q.enqueue(2);
Q.enqueue(3);
Q.enqueue(4);
Q.enqueue(5);
Q.dequeue();
Q.dequeue();
Q.dequeue();
Q.dequeue();
Q.dequeue();
Q.enqueue(1);
Q.dequeue();
Q.enqueue(2);
Q.enqueue(3);
Q.enqueue(4);
Q.enqueue(5);
Q.enqueue(6);
System.out.println(Q.isEmpty());
System.out.println(Q.front());
System.out.println(Q.size());
Q.printCheck();
}
catch(Exception e)
{
System.out.println(e);
}
}
}