forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.php
More file actions
69 lines (56 loc) · 1.5 KB
/
stack.php
File metadata and controls
69 lines (56 loc) · 1.5 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
<?php
/**
* The SplStack class provides the main functionalities of a stack.
* It is integrated into the PHP SPL library which is usable in any PHP application.
*
* @see https://www.php.net/manual/en/class.splstack.php
*/
$stack = new SplStack();
$stack->push(4);
$stack->push(5);
$stack->push(9);
echo $stack->pop(), PHP_EOL; // 9 - Last in first out
echo $stack->count(), PHP_EOL; // 2 - Elements in the stack
echo $stack->top(), PHP_EOL; // 5 - End of the doubly linked list
echo $stack->bottom(), PHP_EOL; // 4 - Begin of the doubly linked list
// Implementation of own Stack
interface StackInterface
{
public function push($value);
public function pop();
public function top();
public function bottom();
public function count();
}
class Stack implements StackInterface
{
private $stack = [];
public function push($value)
{
$this->stack[] = $value;
}
public function pop()
{
return array_pop($this->stack);
}
public function top()
{
return end($this->stack);
}
public function bottom()
{
return reset($this->stack);
}
public function count()
{
return count($this->stack);
}
}
$stack = new Stack();
$stack->push(4);
$stack->push(5);
$stack->push(9);
echo $stack->pop(), PHP_EOL; // 9 - Last in first out
echo $stack->count(), PHP_EOL; // 2 - Elements in the stack
echo $stack->top(), PHP_EOL; // 5 - End of the array
echo $stack->bottom(), PHP_EOL; // 4 - Begin of the array