File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change 27
27
28
28
// Search for a existing title, and a non-existing title.
29
29
var_dump ($ bookTitles ->search ("Introducing PHP to noobs " )->data );
30
- var_dump ($ bookTitles ->search ("Clever stuff " ));
30
+ var_dump ($ bookTitles ->search ("Clever stuff " ));
31
+
32
+ // Insert a title befor another title
33
+ $ bookTitles ->insertBefore ("Handsome developers " , "Programming Intelligence " );
34
+
35
+ $ bookTitles ->display ();
Original file line number Diff line number Diff line change @@ -87,4 +87,30 @@ public function search(string $data = NULL)
87
87
return false ;
88
88
}
89
89
90
+ /**
91
+ * Inserts a new node before an existing node.
92
+ * Care must be taken to set the next values of the node before and the searched node itself to match the inserted node
93
+ * @param string|null $data
94
+ * @param string|null $query
95
+ */
96
+ public function insertBefore (string $ data = null , string $ query = null )
97
+ {
98
+ $ newNode = new ListNode ($ data );
99
+
100
+ if ($ this ->_firstNode ) {
101
+ $ previous = NULL ;
102
+ $ currentNode = $ this ->_firstNode ;
103
+ while ($ currentNode !== NULL ) {
104
+ if ($ currentNode ->data === $ query ) {
105
+ $ newNode ->next = $ currentNode ;
106
+ $ previous ->next = $ newNode ;
107
+ $ this ->_totalNodes ++;
108
+ break ;
109
+ }
110
+ $ previous = $ currentNode ;
111
+ $ currentNode = $ currentNode ->next ;
112
+ }
113
+ }
114
+ }
115
+
90
116
}
You can’t perform that action at this time.
0 commit comments