Repository navigation
Expand file tree
/
Copy pathstack.php
More file actions
103 lines (89 loc) · 1.84 KB
/
Copy pathstack.php
File metadata and controls
103 lines (89 loc) · 1.84 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
/**
* Stack implementation
* Part of Cosmos by OpenGenus Foundation
* Note: To run this script, you need PHP >= 7.1
*
* @author Lucas Soares Candalo <[email protected]>
*/
class Stack
{
/**
* @var array
*/
private $elements = [];
/**
* Removes an item from the stack
*
* @return void
*/
public function pop(): void
{
if (!$this->isEmpty()) {
array_pop($this->elements);
}
}
/**
* Adds an item to the stack
*
* @param int $element
* @return void
*/
public function push(int $element): void
{
array_push($this->elements, $element);
}
/**
* Gets the top element of the stack
*
* @return int
*/
public function peek(): int
{
return end($this->elements);
}
/**
* Checks if the stack is empty
*
* @return bool true if is empty, false otherwise
*/
public function isEmpty(): bool
{
return empty($this->elements);
}
}
class StackPrinter
{
/**
* Print stack elements
*
* @param Stack $stack
* @return void
*/
public function print(Stack $stack): void
{
$stackClone = clone $stack;
echo "Stack elements:\n\n";
while(!$stackClone->isEmpty()) {
echo $stackClone->peek()."\n";
$stackClone->pop();
}
echo "\n\n";
}
}
$stack = new Stack();
$stackPrinter = new StackPrinter();
// Add a few elements to the stack
$stack->push(10);
$stack->push(20);
$stack->push(30);
// Print stack elements
$stackPrinter->print($stack);
// Remove top element from the stack
$stack->pop();
// Print stack elements again
$stackPrinter->print($stack);
// Remove top element from the stack
$stack->pop();
// Print stack elements again
$stackPrinter->print($stack);