You need to take a look at the container holding the Node
items. For a singly-linked-list
there should be a pointer marking the beginning of the list eg: linked_list.BEGIN
.
The function in this snippet would insert a node item at a specified index
bool insert(int index, item value)
{
// invalid index...
if (index < 0) return false;
// list is empty and index is 0...
if ((index == 0) && (linked_list.BEGIN == nullptr))
{
linked_list.BEGIN = new Node(value);
return true;
}
Node *current = linked_list.BEGIN, *prev = nullptr;
int i = 0;
for (; (current != nullptr); ++i)
{
if (i == index) // index is found (index < SIZEOF(linked_list))...
{
Node *ptr = new Node(value);
ptr->next = current;
if (prev != nullptr) prev->next = ptr;
else linked_list.BEGIN = ptr;
break;
}
else // index not found yet...
{
prev = current;
current = current->next;
}
}
// index is found (index == SIZEOF(linked_list))
if ((i == index) && (current == nullptr))
{
prev->next = new Node(value);
}
return (i == index);
}
Note: This snippet is for illustration and not actual code