File tree Expand file tree Collapse file tree 2 files changed +26
-0
lines changed Expand file tree Collapse file tree 2 files changed +26
-0
lines changed Original file line number Diff line number Diff line change 18
18
$ bookTitles ->insert ("Programming Intelligence " );
19
19
20
20
// Display data
21
+ $ bookTitles ->display ();
22
+
23
+ // Insert a new book as the first element of the list.
24
+ $ bookTitles ->insertAtFirst ("Introducing PHP to noobs " );
25
+
21
26
$ bookTitles ->display ();
Original file line number Diff line number Diff line change @@ -46,4 +46,25 @@ public function display()
46
46
}
47
47
}
48
48
49
+ /**
50
+ * Inserts a node as the first node in the linked list.
51
+ * We need to take care to set the previous first node as the next value of the inserted node.
52
+ * @param string|null $data
53
+ * @return bool
54
+ */
55
+ public function insertAtFirst (string $ data = NULL )
56
+ {
57
+ $ newNode = new ListNode ($ data );
58
+
59
+ if ($ this ->_firstNode === NULL ) {
60
+ $ this ->_firstNode = &$ newNode ;
61
+ } else {
62
+ $ currentFirstNode = $ this ->_firstNode ;
63
+ $ this ->_firstNode = &$ newNode ;
64
+ $ newNode ->next = $ currentFirstNode ;
65
+ }
66
+ $ this ->_totalNodes ++;
67
+ return true ;
68
+ }
69
+
49
70
}
You can’t perform that action at this time.
0 commit comments