-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStack.php
139 lines (128 loc) · 2.13 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?php
/**
* 顺序栈
*
* User: yangyu
* Date: 16/9/21
* Time: 上午9:30
*/
class Stack
{
/**
* @var array
*/
public $array;
/**
* @var int
*/
public $top;
/**
* 构造栈
*
* Stack constructor.
* @param array $arr
*/
public function __construct(array $arr = [])
{
$this->array = $arr;
$this->top = count($arr) - 1;
}
/**
*摧毁栈
*/
public function destroyStack()
{
$this->array = null;
$this->top = -1;
}
/**
*清空栈
*/
public function clearStack()
{
$this->array = [];
$this->top = -1;
}
/**
* 判断是否为空
*
* @return bool
*/
public function emptyStack()
{
if (count($this->array) == 0) {
return true;
} else {
return false;
}
}
/**
* 栈的长度
*
* @return int
*/
public function stackLength()
{
return count($this->array);
}
/**
* 获取元素
*
* @return mixed|string
*/
public function getTop()
{
if ($this->top == -1) {
return 'Error';
}
return $this->array[$this->top];
}
/**
* 入栈
*
* @param $elem
*/
public function push($elem)
{
$this->top++;
$this->array[$this->top] = $elem;
}
/**
* 出栈
*
* @return mixed|string
*/
public function pop()
{
if ($this->top == -1) {
return 'Error';
}
$del = $this->array[$this->top];
unset($this->array[$this->top]);
$this->top--;
return $del;
}
/**
* 遍历
*
* @return array|null
*/
public function stackTraverse()
{
if (is_null($this->array)) {
return null;
}
$arr = [];
for ($i = 0; $i <= $this->top; $i++){
$arr[] = $this->array[$i];
}
return$arr;
}
/**
* @return array
*/
public function stackTraverse2()
{
return $this->array;
}
}