1
+ <?php
2
+ /**
3
+ * Created by PhpStorm.
4
+ * User: bert
5
+ * Date: 4/10/18
6
+ * Time: 9:09
7
+ */
8
+
9
+ namespace App \Chapter04 ;
10
+
11
+
12
+ use OverflowException ;
13
+ use UnderflowException ;
14
+
15
+ class CircularQueue implements Queue
16
+ {
17
+
18
+ private $ queue ;
19
+ private $ limit ;
20
+ private $ front = 0 ;
21
+ private $ rear = 0 ;
22
+
23
+ /**
24
+ * CircularQueue constructor.
25
+ * @param $limit
26
+ */
27
+ public function __construct (int $ limit = 5 )
28
+ {
29
+ $ this ->limit = $ limit ;
30
+ $ this ->queue = [];
31
+ }
32
+
33
+ /**
34
+ * Returns the size of the Circular queue.
35
+ * This is calculated by either substracting the front position from the rear position or by substracting the sum
36
+ * of the front and rear positions from the total limit.
37
+ * @return int
38
+ */
39
+ public function size ()
40
+ {
41
+ if ($ this ->rear > $ this ->front ){
42
+ return $ this ->rear - $ this ->front ;
43
+ }
44
+
45
+ return $ this ->limit - $ this ->front + $ this ->rear ;
46
+ }
47
+
48
+ /**
49
+ * Add an item to the rear of the queue.
50
+ * @param string $item
51
+ * @return mixed
52
+ */
53
+ public function enqueue (string $ item )
54
+ {
55
+ if ($ this ->isFull ()){
56
+ throw new OverflowException ("Queue is full. " );
57
+ } else {
58
+ $ this ->queue [$ this ->rear ] = $ item ;
59
+ // get the last position by using a rest division by the total limit.
60
+ $ this ->rear = ($ this ->rear + 1 ) % $ this ->limit ;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Remove an item from the front of the queue.
66
+ * @return mixed|string
67
+ */
68
+ public function dequeue ()
69
+ {
70
+ $ item = "" ;
71
+ if ($ this ->isEmpty ()){
72
+ throw new UnderflowException ("Queue is empty " );
73
+ } else {
74
+ $ item = $ this ->queue [$ this ->front ];
75
+ $ this ->queue [$ this ->front ] = NULL ;
76
+ $ this ->front = ($ this ->front + 1 ) % $ this ->limit ;
77
+ }
78
+
79
+ return $ item ;
80
+ }
81
+
82
+ /**
83
+ * Returns the front item of the queue, without removing it.
84
+ * @return string
85
+ */
86
+ public function peek () : string
87
+ {
88
+ return $ this ->queue [$ this ->front ];
89
+ }
90
+
91
+ /**
92
+ * Check whether the queue is empty.
93
+ * @return bool
94
+ */
95
+ public function isEmpty () : bool
96
+ {
97
+ return $ this ->front == $ this ->rear ;
98
+ }
99
+
100
+ /**
101
+ * Check whether the queue is full.
102
+ * @return bool
103
+ */
104
+ public function isFull () : bool
105
+ {
106
+ $ diff = $ this ->rear - $ this ->front ;
107
+ if ($ diff == -1 || $ diff == ($ this ->limit - 1 )){
108
+ return true ;
109
+ }
110
+
111
+ return false ;
112
+ }
113
+ }
0 commit comments