-
-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathstack.php
More file actions
82 lines (68 loc) · 1.36 KB
/
stack.php
File metadata and controls
82 lines (68 loc) · 1.36 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
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
<?php
/**
* @template T
*/
interface IStack
{
/**
* Removes the last element from the stack and returns it.
* @return T | null
*/
public function pop();
/**
* Adds an element at the end of the stack and returns the new size.
* @param T $element
*/
public function push($element): int;
/**
* Returns the length of the stack.
*/
public function size(): int;
/**
* Returns the first element of the stack.
* @return T
*/
public function top();
}
/**
* @template T
* @implements IStack<T>
*/
class Stack implements IStack
{
/**
* @var array<T> $elements
*/
private $elements = [];
public function pop()
{
return array_pop($this->elements);
}
public function push($element): int
{
array_push($this->elements, $element);
return $this->size();
}
public function size(): int
{
return count($this->elements);
}
public function top()
{
return $this->elements[0];
}
}
function example_stack(): void
{
/**
* @var Stack<int> $int_stack
*/
$int_stack = new Stack();
$int_stack->push(4);
$int_stack->push(5);
$int_stack->push(7);
echo $int_stack->pop() . "\n"; // 7
echo $int_stack->size() . "\n"; // 2
echo $int_stack->top() . "\n"; // 4
}
example_stack();