Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RakhmedovRS/c032fe01f6ac4679295c1ef1ec5c1f31 to your computer and use it in GitHub Desktop.
Save RakhmedovRS/c032fe01f6ac4679295c1ef1ec5c1f31 to your computer and use it in GitHub Desktop.
/**
* Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
*/
public void addAtIndex(int index, int val)
{
if (index < 0 || index > size)
{
return;
}
else if (index == 0)
{
addAtHead(val);
return;
}
else if (index == size)
{
addAtTail(val);
return;
}
Link current = head;
Link link = new Link(val);
while (index-- > 0)
{
current = current.next;
}
//-->
link.next = current.next;
current.next.prev = link;
//<--
current.next = link;
link.prev = current;
size++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment