Skip to content

Commit 1e9b572

Browse files
committed
Added function to insert a node at specified position in linked list
1 parent eca7a0e commit 1e9b572

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

data_structures/Lists/SinglyLinkedList.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,36 @@ public void insertHead(int x){
3434
head = newNode; //Now set the new link to be the head
3535
}
3636

37+
38+
/**
39+
* Inserts a new node at a specified position
40+
* @param head head node of the linked list
41+
* @param data data to be stored in a new node
42+
* @param position position at which a new node is to be inserted
43+
* @return reference of the head of the linked list
44+
*/
45+
46+
Node InsertNth(Node head, int data, int position) {
47+
48+
Node newNode = new Node();
49+
newNode.data = data;
50+
51+
if (position == 0) {
52+
newNode.next = head;
53+
return newNode;
54+
}
55+
56+
Node current = head;
57+
58+
while (--position > 0) {
59+
current = current.next;
60+
}
61+
62+
newNode.next = current.next;
63+
current.next = newNode;
64+
return head;
65+
}
66+
3767
/**
3868
* This method deletes an element at the head
3969
*

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy