Created
July 10, 2022 22:52
-
-
Save RakhmedovRS/c032fe01f6ac4679295c1ef1ec5c1f31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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