/
CircularQueue.php
61 lines (48 loc) 路 1.21 KB
/
CircularQueue.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
<?php
namespace DataStructure\Queue;
class CircularQueue implements QueueInterface
{
private $queue;
private $limit;
private $front = 0;
private $rear = 0;
public function __construct(int $limit = 0)
{
$this->limit = $limit;
$this->queue = [];
}
public function isEmpty()
{
return $this->front === $this->rear;
}
public function isFull()
{
$diff = $this->rear - $this->front;
if ($diff == -1 || $diff == ($this->limit - 1)) {
return true;
}
return false;
}
public function peek()
{
return $this->queue[$this->front];
}
public function dequeue()
{
if ($this->isEmpty()) {
throw new \UnderflowException('Queue is empty');
}
$item = $this->queue[$this->front];
$this->queue[$this->front] = null;
$this->front = ($this->front + 1) % $this->limit;
return $item;
}
public function enqueue(string $item)
{
if ($this->isFull()) {
throw new \OverflowException('Queue is full');
}
$this->queue[$this->rear] = $item;
$this->rear = ($this->rear + 1) % $this->limit;
}
}