Skip to content

Commit aec556f

Browse files
committed
Added Stack as a Linked List example
1 parent 786396d commit aec556f

File tree

3 files changed

+107
-0
lines changed

3 files changed

+107
-0
lines changed

chap-04/stack-as-linked-list.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 3/10/18
6+
* Time: 16:34
7+
*/
8+
9+
use App\Chapter04\BookList;
10+
11+
require_once __DIR__ . '/../vendor/autoload.php';
12+
13+
try {
14+
$programmingBooks = new BookList();
15+
$programmingBooks->push("Introduction to PHP7");
16+
$programmingBooks->push("Mastering Javascript");
17+
$programmingBooks->push("MySQL Workbench tutorial");
18+
19+
echo $programmingBooks->pop() . PHP_EOL;
20+
echo $programmingBooks->pop() . PHP_EOL;
21+
echo $programmingBooks->top() . PHP_EOL;
22+
} catch (Exception $e) {
23+
echo $e->getMessage();
24+
}

src/Chapter03/LinkedList.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,4 +327,14 @@ public function rewind()
327327
$this->_currentPosition = 0;
328328
$this->_currentNode = $this->_firstNode;
329329
}
330+
331+
332+
/**
333+
* Return the size of the list (ie. the number of nodes).
334+
* @return int
335+
*/
336+
public function getSize()
337+
{
338+
return $this->_totalNodes;
339+
}
330340
}

src/Chapter04/BookList.php

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 3/10/18
6+
* Time: 16:23
7+
*/
8+
9+
namespace App\Chapter04;
10+
11+
12+
use App\Chapter03\LinkedList;
13+
use UnderflowException;
14+
15+
class BookList implements Stack
16+
{
17+
18+
private $stack;
19+
20+
/**
21+
* BookList constructor.
22+
* @param $stack
23+
*/
24+
public function __construct()
25+
{
26+
$this->stack = new LinkedList();
27+
}
28+
29+
30+
/**
31+
* Adds an item to the stack.
32+
* @param string $item
33+
* @return mixed
34+
*/
35+
public function push(string $item)
36+
{
37+
$this->stack->insert($item);
38+
}
39+
40+
/**
41+
* Removes an item from the stack.
42+
* @return string
43+
*/
44+
public function pop() : string
45+
{
46+
if ($this->isEmpty()){
47+
throw new UnderflowException("Stack is empty.");
48+
} else {
49+
$lastItem = $this->top();
50+
$this->stack->deleteLast();
51+
return $lastItem;
52+
}
53+
}
54+
55+
/**
56+
* Returns the top element of the stack.
57+
* @return mixed
58+
*/
59+
public function top()
60+
{
61+
return $this->stack->getItemByPosition($this->stack->getSize())->data;
62+
}
63+
64+
/**
65+
* Returns whether the stack is empty.
66+
* @return bool
67+
*/
68+
public function isEmpty()
69+
{
70+
return $this->stack->getSize() == 0;
71+
}
72+
73+
}

0 commit comments

Comments
 (0)