@@ -93,7 +93,7 @@ public function search(string $data = NULL)
93
93
* @param string|null $data
94
94
* @param string|null $query
95
95
*/
96
- public function insertBefore (string $ data = null , string $ query = null )
96
+ public function insertBefore (string $ data = NULL , string $ query = NULL )
97
97
{
98
98
$ newNode = new ListNode ($ data );
99
99
@@ -113,4 +113,35 @@ public function insertBefore(string $data = null, string $query = null)
113
113
}
114
114
}
115
115
116
+ /**
117
+ * Inserts a new node before an existing node.
118
+ * Care must be taken to set the next values of the node after and the searched node itself
119
+ * @param string|null $data
120
+ * @param string|null $query
121
+ */
122
+ public function insertAfter (string $ data = NULL , string $ query = NULL )
123
+ {
124
+ $ newNode = new ListNode ($ data );
125
+
126
+ if ($ this ->_firstNode ) {
127
+ $ nextNode = NULL ;
128
+ $ currentNode = $ this ->_firstNode ;
129
+ while ($ currentNode !== NULL ) {
130
+ if ($ currentNode ->data === $ query ) {
131
+ if ($ nextNode !== NULL ) {
132
+ $ newNode ->next = $ nextNode ;
133
+ }
134
+ $ currentNode ->next = $ newNode ;
135
+ $ this ->_totalNodes ++;
136
+ break ;
137
+ }
138
+ $ currentNode = $ currentNode ->next ;
139
+ // We can only set the next Node if a value exists for next in the current node.
140
+ if (isset ($ currentNode ->next )) {
141
+ $ nextNode = $ currentNode ->next ;
142
+ }
143
+ }
144
+ }
145
+ }
146
+
116
147
}
0 commit comments