-
Notifications
You must be signed in to change notification settings - Fork 143
/
LinkedListStack.php
47 lines (39 loc) · 1009 Bytes
/
LinkedListStack.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
<?php
namespace DataStructure\Stack;
use DataStructure\LinkedList\LinkedList;
class LinkedListStack implements StackInterface
{
private $stack;
private $limit;
public function __construct(int $limit)
{
$this->limit = $limit;
$this->stack = new LinkedList();
}
public function top()
{
return $this->stack->getNthNode($this->stack->getSize() - 1)->data;
}
public function isEmpty()
{
return $this->stack->getSize() === 0;
}
public function pop()
{
if ($this->isEmpty()) {
throw new \UnderflowException('stack is empty');
} else {
$lastItem = $this->top();
$this->stack->deleteLast();
return $lastItem;
}
}
public function push(string $item)
{
if ($this->stack->getSize() < $this->limit) {
$this->stack->insert($item);
} else {
throw new \OverflowException('stack is overflow');
}
}
}