This repository was archived by the owner on Sep 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathstack.php
More file actions
112 lines (101 loc) · 2.18 KB
/
Copy pathstack.php
File metadata and controls
112 lines (101 loc) · 2.18 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
104
105
106
107
108
109
110
111
112
<?php
/**
* @author Jan Tabacki
*
*
* Implemtaion of Stack data structure
* Stack follows LIFO (Last In First Out) priniciple
* For Insertion and Deletion its complexity is O(1)
* For Accessing and Searching its complexity is O(n)
*/
class Stack
{
private $first;
private $last;
private $size;
public function __construct()
{
$this->first = null;
$this->last = null;
$this->size = 0;
}
/**
* Adding data to Top of the stack
* @param {*} data
* @returns {Stack}
*/
public function push($data)
{
$newNode = new Node($data);
if (!$this->first) {
$this->first = $newNode;
$this->last = $newNode;
} else {
$temp = $this->first;
$this->first = $newNode;
$this->first->next = $temp;
}
$this->size++;
return $this;
}
/**
* Removing data frpm Top of the stack
* @returns {Node.data} The data that is removing from the stack
*/
public function pop()
{
if (!$this->first) {
throw new Exception('UNDERFLOW :::: Stack is empty, there is nothing to remove');
}
$current = $this->first;
if ($this->first === $this->last) {
$this->last = null;
}
$this->first = $current->next;
$this->size--;
return $current->data;
}
/**
* @returns {Node.data} Top most element of the stack
*/
public function peek()
{
if (!$this->first) {
throw new Exception('Stack is empty');
}
return $this->first->data;
}
/**
* @returns size of the Stack
*/
public function size()
{
return $this->size;
}
/**
* @returns if Stack is empty
*/
public function isEmpty()
{
return $this->size == 0;
}
/**
* clears the Stack
*/
public function clear()
{
$this->first = null;
$this->last = null;
$this->size = 0;
}
}
class Node
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = null;
}
}