1
+ /*
2
+ * A queue data structure functions the same as a real world queue.
3
+ * The elements that are added first are the first to be removed.
4
+ * New elements are added to the back/rear of the queue.
5
+ */
6
+ class Queue {
7
+ private int maxSize ;
8
+ private int [] queueArray ;
9
+ private int front ;
10
+ private int rear ;
11
+ private int nItems ;
12
+
13
+ public Queue (int size ){ //Constructor
14
+ maxSize = size ;
15
+ queueArray = new int [size ];
16
+ front = 0 ;
17
+ rear = -1 ;
18
+ nItems = 0 ;
19
+ }
20
+
21
+ public boolean insert (int x ){ //Inserts an element at the rear of the queue
22
+ if (isFull ())
23
+ return false ;
24
+ if (rear == maxSize -1 ) //If the back of the queue is the end of the array wrap around to the front
25
+ rear = -1 ;
26
+ rear ++;
27
+ queueArray [rear ] = x ;
28
+ nItems ++;
29
+ return true ;
30
+ }
31
+
32
+ public int remove (){ //Remove an element from the front of the queue
33
+ if (isEmpty ()){
34
+ System .out .println ("Queue is empty" );
35
+ return -1 ;
36
+ }
37
+ int temp = queueArray [front ];
38
+ front ++;
39
+ if (front == maxSize ) //Dealing with wrap-around again
40
+ front = 0 ;
41
+ nItems --;
42
+ return temp ;
43
+ }
44
+
45
+ public int peekFront (){ //Checks what's at the front of the queue
46
+ return queueArray [front ];
47
+ }
48
+
49
+ public int peekRear (){ //Checks what's at the rear of the queue
50
+ return queueArray [rear ];
51
+ }
52
+
53
+ public boolean isEmpty (){ //Returns true is the queue is empty
54
+ return (nItems == 0 );
55
+ }
56
+
57
+ public boolean isFull (){ //Returns true is the queue is full
58
+ return (nItems == maxSize );
59
+ }
60
+
61
+ public int getSize (){ //Returns the number of elements in the queue
62
+ return nItems ;
63
+ }
64
+ }
65
+ //Example
66
+ public class Queues {
67
+ public static void main (String args []){
68
+ Queue myQueue = new Queue (4 );
69
+ myQueue .insert (10 );
70
+ myQueue .insert (2 );
71
+ myQueue .insert (5 );
72
+ myQueue .insert (3 );
73
+ //[10(front), 2, 5, 3(rear)]
74
+
75
+ System .out .println (myQueue .isFull ()); //Will print true
76
+
77
+ myQueue .remove (); //Will make 2 the new front, making 10 no longer part of the queue
78
+ //[10, 2(front), 5, 3(rear)]
79
+
80
+ myQueue .insert (7 ); //Insert 7 at the rear which will be index 0 because of wrap around
81
+ // [7(rear), 2(front), 5, 3]
82
+
83
+ System .out .println (myQueue .peekFront ()); //Will print 2
84
+ System .out .println (myQueue .peekRear ()); //Will print 7
85
+ }
86
+ }
0 commit comments