Skip to content

Instantly share code, notes, and snippets.

@zivce
Created April 3, 2021 20:33
Show Gist options
  • Save zivce/6557ddf6c6389a82c8965c898604492d to your computer and use it in GitHub Desktop.
Save zivce/6557ddf6c6389a82c8965c898604492d to your computer and use it in GitHub Desktop.
public static Node<Integer> InsertRecursively(Node<Integer>head,int position,int element)
{
if(head==null && position>0)//Note this is not the base case
//this is the case when linked list is empty and adding at position other than 0
{
return head;
}
//Base Case
if(position==0)
{
Node<Integer>newNode=new Node<Integer>(element);
newNode.next=head;//since we are inserting between (position-1) and (position)
//therefore newNode.next should point to current head
return newNode;
}
Node<Integer> next=InsertRecursively(head.next, position-1, element);
head.next=next;
return head;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment