Skip to content

Commit 5733234

Browse files
committed
Added abstract example of Circular Linked List
1 parent 7287794 commit 5733234

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

src/Chapter03/CircularLinkedList.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: bert
5+
* Date: 3/10/18
6+
* Time: 9:23
7+
*/
8+
9+
namespace App\Chapter03;
10+
11+
12+
class CircularLinkedList
13+
{
14+
private $_firstNode = NULL;
15+
private $_totalNodes = 0;
16+
17+
/**
18+
* Insert new node at end of circular linked list.
19+
* We must take care to set the next propery of the inserted node to the first node of the list.
20+
* @param string|null $data
21+
* @return bool
22+
*/
23+
public function insertAtEnd(string $data = NULL)
24+
{
25+
$newNode = new ListNode($data);
26+
if ($this->_firstNode === NULL){
27+
$this->_firstNode = &$newNode;
28+
} else {
29+
$currenNode = $this->_firstNode;
30+
while ($currenNode->next !== $this->_firstNode){
31+
$currenNode = $currenNode->next;
32+
}
33+
$currenNode->next = $newNode;
34+
}
35+
$newNode->next = $this->_firstNode;
36+
$this->_totalNodes++;
37+
return true;
38+
}
39+
40+
/**
41+
* Display function for a circular linked list.
42+
* We cannot use the same method of a normal linked list : we need to take care not to fall into an infinite loop
43+
* because of the next property of the last node.
44+
*/
45+
public function display()
46+
{
47+
echo "Total book titles: " .$this->_totalNodes . PHP_EOL;
48+
$currentNode = $this->_firstNode;
49+
while ($currentNode->next !== $this->_firstNode){
50+
echo $currentNode->data . PHP_EOL;
51+
}
52+
53+
if ($currentNode){
54+
echo $currentNode->data . PHP_EOL;
55+
}
56+
}
57+
58+
}

0 commit comments

Comments
 (0)