-
-
Notifications
You must be signed in to change notification settings - Fork 491
/
Copy pathQueue.php
80 lines (63 loc) · 1.53 KB
/
Queue.php
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
<?php
/**
* Queue Data Structure - FIFO (First In, First Out)
*/
class Queue
{
private array $elements;
private int $count;
private int $lowestCount;
public function __construct()
{
$this->elements = [];
$this->count = 0;
$this->lowestCount = 0;
}
public function enqueue($element): void
{
$this->elements[$this->count] = $element;
$this->count++;
}
public function dequeue()
{
if ($this->isEmpty()) {
return null;
}
$element = $this->elements[$this->lowestCount];
unset($this->elements[$this->lowestCount]);
$this->lowestCount++;
return $element;
}
public function isEmpty(): bool
{
return $this->count - $this->lowestCount === 0;
}
public function size(): int
{
return $this->count - $this->lowestCount;
}
public function peek()
{
if ($this->isEmpty()) {
return null;
}
return $this->elements[$this->lowestCount];
}
public function clear(): void
{
$this->elements = [];
$this->count = 0;
$this->lowestCount = 0;
}
public function toString(string $delimiter = ''): string
{
if ($this->isEmpty()) {
return '';
}
$result = "{$this->elements[$this->lowestCount]}";
for ($i = $this->lowestCount + 1; $i < $this->count; $i++) {
$result .= "{$delimiter}{$this->elements[$i]}";
}
return $result;
}
}