-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathMyStackAnother.php
74 lines (59 loc) · 1.45 KB
/
MyStackAnother.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
<?php
/**
* code-segment
*
* @author liu hao<liu546hao@163.com>
* @copyright liu hao<liu546hao@163.com>
*/
namespace PHPCodes\InterestingQuestion\Stack\StackWithGetMin;
class MyStackAnother extends AbstractMyStack
{
/**
* @var null|\SplStack
*/
private $dataStack = null;
/**
* @var null|\SplStack
*/
private $minStack = null;
public function __construct()
{
$this->dataStack = new \SplStack();
$this->minStack = new \SplStack();
}
public function push($value)
{
$this->dataStack->push($value);
if (!$this->minStack->isEmpty()) {
$current = $this->minStack->top();
if ($current > $value) {
$this->minStack->push($value);
} else {
$this->minStack->push($current);
}
} else {
$this->minStack->push($value);
}
}
public function pop()
{
if ($this->dataStack->isEmpty()) {
throw new \RuntimeException("stack is empty");
}
$value = $this->dataStack->pop();
$this->minStack->pop();
return $value;
}
public function getMin()
{
if ($this->dataStack->isEmpty()) {
throw new \RuntimeException("stack is empty");
}
$value = $this->minStack->top();
return $value;
}
public function isEmpty()
{
return $this->dataStack->isEmpty();
}
}