ImplementQueueUsingStacks   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
eloc 20
c 2
b 0
f 0
dl 0
loc 42
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A pop() 0 8 2
A peek() 0 7 2
A empty() 0 3 2
A push() 0 11 4
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