DEV Community

k@k
k@k

Posted on

Add a node at specific position in LinkedList

A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty.

As an example, if your list starts as 1->2->3 and you want to insert a node at position 2 with data =4, your new list should be 1->2->4->3

Function Description Complete the function insertNodeAtPosition in the editor below. It must return a reference to the head node of your finished list.

insertNodeAtPosition has the following parameters:

head: a SinglyLinkedListNode pointer to the head of the list

data: an integer value to insert as data in your new node

position: an integer position to insert the new node, zero-based indexing

/*
 * For your reference:
 *
 * SinglyLinkedListNode {
 *     int data;
 *     SinglyLinkedListNode next;
 * }
 */

static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode head, int data, int position) {
SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
if(head == null){
return newNode;
}
else if(position == 0){
newNode.next = head;
return newNode;
}
SinglyLinkedListNode cur = head;
for(int i=0;i<position-1;i++){
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
return head; }

Note: Please share your ideas for any programming language......

Top comments (0)