ImplementQueueUsingStacks2::peek()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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