ImplementQueueUsingStacks::peek()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 3
c 2
b 0
f 0
dl 0
loc 7
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class ImplementQueueUsingStacks
8
{
9
    private array $cache = [];
10
    private array $stack = [];
11
    private ?int $front;
12
13
    public function push(int $value): void
14
    {
15
        if (empty($this->stack)) {
16
            $this->front = $value;
17
        }
18
        while (!empty($this->stack)) {
19
            $this->cache[] = array_shift($this->stack);
20
        }
21
        $this->cache[] = $value;
22
        while (!empty($this->cache)) {
23
            $this->stack[] = array_shift($this->cache);
24
        }
25
    }
26
27
    public function pop(): ?int
28
    {
29
        $value = array_shift($this->stack);
30
        if (!empty($this->stack)) {
31
            $this->front = current($this->stack);
32
        }
33
34
        return $value;
35
    }
36
37
    public function peek(): ?int
38
    {
39
        if (empty($this->stack)) {
40
            return null;
41
        }
42
43
        return $this->front;
44
    }
45
46
    public function empty(): bool
47
    {
48
        return count($this->stack) === 0 && count($this->cache) === 0;
49
    }
50
}
51