Added function to insert a node at specified position in linked list

This commit is contained in:
Atishaya Jain 2017-08-15 23:04:08 +05:30
parent eca7a0ee28
commit 1e9b5724df

View File

@ -34,6 +34,36 @@ class SinglyLinkedList{
head = newNode; //Now set the new link to be the head
}
/**
* Inserts a new node at a specified position
* @param head head node of the linked list
* @param data data to be stored in a new node
* @param position position at which a new node is to be inserted
* @return reference of the head of the linked list
*/
Node InsertNth(Node head, int data, int position) {
Node newNode = new Node();
newNode.data = data;
if (position == 0) {
newNode.next = head;
return newNode;
}
Node current = head;
while (--position > 0) {
current = current.next;
}
newNode.next = current.next;
current.next = newNode;
return head;
}
/**
* This method deletes an element at the head
*