Created
April 3, 2021 20:33
-
-
Save zivce/6557ddf6c6389a82c8965c898604492d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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