-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathImplementQueueUsingStacks.php
More file actions
50 lines (41 loc) · 1 KB
/
ImplementQueueUsingStacks.php
File metadata and controls
50 lines (41 loc) · 1 KB
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
<?php
declare(strict_types=1);
namespace leetcode;
class ImplementQueueUsingStacks
{
private array $cache = [];
private array $stack = [];
private ?int $front;
public function push(int $value): void
{
if (empty($this->stack)) {
$this->front = $value;
}
while (!empty($this->stack)) {
$this->cache[] = array_shift($this->stack);
}
$this->cache[] = $value;
while (!empty($this->cache)) {
$this->stack[] = array_shift($this->cache);
}
}
public function pop(): ?int
{
$value = array_shift($this->stack);
if (!empty($this->stack)) {
$this->front = current($this->stack);
}
return $value;
}
public function peek(): ?int
{
if (empty($this->stack)) {
return null;
}
return $this->front;
}
public function empty(): bool
{
return count($this->stack) === 0 && count($this->cache) === 0;
}
}