From 1e9b5724dfafc69c3daabd02c3e7c3379f52dd60 Mon Sep 17 00:00:00 2001 From: Atishaya Jain Date: Tue, 15 Aug 2017 23:04:08 +0530 Subject: [PATCH] Added function to insert a node at specified position in linked list --- data_structures/Lists/SinglyLinkedList.java | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/data_structures/Lists/SinglyLinkedList.java b/data_structures/Lists/SinglyLinkedList.java index c5a4ae08..32747cf2 100644 --- a/data_structures/Lists/SinglyLinkedList.java +++ b/data_structures/Lists/SinglyLinkedList.java @@ -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 *