-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathStack.php
111 lines (99 loc) · 2.19 KB
/
Stack.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
declare(strict_types=1);
namespace Psl\DataStructure;
use function array_pop;
use function count;
/**
* A basic implementation of a stack data structure ( LIFO ).
*
* @template T
*
* @implements StackInterface<T>
*/
final class Stack implements StackInterface
{
/**
* @var list<T> $items
*/
private array $items = [];
/**
* Provides a default instance of the {@see Stack}.
*
* @return static A new instance of {@see Stack}, devoid of any items.
*
* @pure
*/
public static function default(): static
{
return new self();
}
/**
* Adds an item to the stack.
*
* @param T $item
*
* @psalm-external-mutation-free
*/
#[\Override]
public function push(mixed $item): void
{
$this->items[] = $item;
}
/**
* Retrieves, but does remove, the most recently added item that was not yet removed,
* or returns null if this queue is empty.
*
* @return null|T
*
* @psalm-mutation-free
*/
#[\Override]
public function peek(): mixed
{
$items = $this->items;
return array_pop($items);
}
/**
* Retrieves and removes the most recently added item that was not yet removed,
* or returns null if this queue is empty.
*
* @return null|T
*
* @psalm-external-mutation-free
*/
#[\Override]
public function pull(): mixed
{
return array_pop($this->items);
}
/**
* Retrieve and removes the most recently added item that was not yet removed.
*
* @throws Exception\UnderflowException If the stack is empty.
*
* @return T
*
* @psalm-external-mutation-free
*/
#[\Override]
public function pop(): mixed
{
if ([] === $this->items) {
throw new Exception\UnderflowException('Cannot pop an item from an empty stack.');
}
/** @var T */
return array_pop($this->items);
}
/**
* Count the items in the stack.
*
* @return int<0, max>
*
* @psalm-mutation-free
*/
#[\Override]
public function count(): int
{
return count($this->items);
}
}