File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments