-
-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathqueue.php
81 lines (68 loc) · 1.4 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
81
<?php
/**
* @template T
*/
interface IQueue
{
/**
* Removes the first element from the queue and returns it.
* @return T | null
*/
public function dequeue();
/**
* Adds an element at the end of the queue and returns the new size.
* @param T $element
*/
public function enqueue($element): int;
/**
* Returns the length of the queue.
*/
public function size(): int;
/**
* Returns the first element of the queue.
* @return T
*/
public function front();
}
/**
* @template T
* @implements IQueue<T>
*/
class Queue implements IQueue
{
/**
* @var array<T> $elements
*/
private $elements = [];
public function dequeue()
{
return array_shift($this->elements);
}
public function enqueue($element): int
{
array_push($this->elements, $element);
return $this->size();
}
public function size(): int
{
return count($this->elements);
}
public function front()
{
return $this->elements[0];
}
}
function example_queue(): void
{
/**
* @var Queue<int> $int_queue
*/
$int_queue = new Queue();
$int_queue->enqueue(4);
$int_queue->enqueue(5);
$int_queue->enqueue(7);
echo $int_queue->dequeue() . "\n"; // 4
echo $int_queue->size() . "\n"; // 2
echo $int_queue->front() . "\n"; // 5
}
example_queue();