Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active August 22, 2020 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbvf50mobile/6690570398d993ebda8c0f50f0227341 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/6690570398d993ebda8c0f50f0227341 to your computer and use it in GitHub Desktop.
Just PHP FUN 083.
<?php
# https://www.codewars.com/kata/55cacc3039607536c6000081 Linked Lists - Insert Nth Node.
function insert_nth($head, $index, $data) {
if(!$head) return new Node($data);
if(0 == $index) return new Node($data,$head);
$prv = null; $nxt = $head; $input = new Node($data);
for($i = 0; $i < $index && $nxt; $i += 1){
$prv = $nxt; $nxt = $nxt->next;
}
if($i != $index) throw new InvalidArgumentException('Division by zero.');
$prv->next = $input;
$input->next = $nxt;
return $head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment