File tree Expand file tree Collapse file tree 2 files changed +104
-0
lines changed Expand file tree Collapse file tree 2 files changed +104
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+ /**
3
+ * Created by PhpStorm.
4
+ * User: bert
5
+ * Date: 3/10/18
6
+ * Time: 22:33
7
+ */
8
+
9
+ use App \Chapter04 \AgentQueueList ;
10
+
11
+ require_once __DIR__ . "/../vendor/autoload.php " ;
12
+
13
+ try {
14
+ $ agents = new AgentQueueList (10 );
15
+ $ agents ->enqueue ("Fred " );
16
+ $ agents ->enqueue ("John " );
17
+ $ agents ->enqueue ("Keith " );
18
+ $ agents ->enqueue ("Adiyan " );
19
+ $ agents ->enqueue ("Michael " );
20
+
21
+ echo $ agents ->dequeue () . PHP_EOL ;
22
+ echo $ agents ->dequeue () . PHP_EOL ;
23
+ echo $ agents ->peek () . PHP_EOL ;
24
+
25
+ } catch (Exception $ e ){
26
+ echo $ e ->getMessage ();
27
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+ /**
3
+ * Created by PhpStorm.
4
+ * User: bert
5
+ * Date: 3/10/18
6
+ * Time: 22:27
7
+ */
8
+
9
+ namespace App \Chapter04 ;
10
+
11
+
12
+ use App \Chapter03 \LinkedList ;
13
+ use OverflowException ;
14
+ use UnderflowException ;
15
+
16
+ class AgentQueueList implements Queue
17
+ {
18
+ private $ limit ;
19
+ private $ queue ;
20
+
21
+ /**
22
+ * AgentQueueList constructor.
23
+ * @param $limit
24
+ */
25
+ public function __construct (int $ limit = 20 )
26
+ {
27
+ $ this ->limit = $ limit ;
28
+ $ this ->queue = new LinkedList ();
29
+ }
30
+
31
+ /**
32
+ * Add an item to the rear of the queue.
33
+ * @param string $item
34
+ * @return mixed
35
+ */
36
+ public function enqueue (string $ item )
37
+ {
38
+ if ($ this ->queue ->getSize () < $ this ->limit ){
39
+ $ this ->queue ->insert ($ item );
40
+ } else {
41
+ throw new OverflowException ("Queue is full " );
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Remove an item from the front of the queue.
47
+ * @return mixed
48
+ */
49
+ public function dequeue () : string
50
+ {
51
+ if ($ this ->isEmpty ()){
52
+ throw new UnderflowException ("Queue is empty " );
53
+ } else {
54
+ $ lastItem = $ this ->peek ();
55
+ $ this ->queue ->deleteFirst ();
56
+ return $ lastItem ;
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Returns the front item of the queue, without removing it.
62
+ * @return mixed
63
+ */
64
+ public function peek () : string
65
+ {
66
+ return $ this ->queue ->getItemByPosition (1 )->data ;
67
+ }
68
+
69
+ /**
70
+ * Check whether the queue is empty.
71
+ * @return mixed
72
+ */
73
+ public function isEmpty () : bool
74
+ {
75
+ return $ this ->queue ->getSize () == 0 ;
76
+ }
77
+ }
You can’t perform that action at this time.
0 commit comments