This is very confusing, uses terms that probably only you know what it means.
A linked list is still a list, you can insert new elements into it at the beginning, at the end and in the middle, as in every list. Her difference to other lists is the cost of doing this. One of the advantages of the linked list is to be able to insert in the medium with complexity O(1), that is, it is constant, the lowest possible. Of course, it has this cost if you are in the position you want, if you are not, and often it does not have a cost of commuting there, and this cost which in many other lists is O(1), in the linked list the cost is O(n). The method you enter in the middle of the list is add()
. In what his signature requires an index, this index is to be used in a get()
internal. What happens if you put a non-existent index number on a get()
, gives track error, right?
If the list has 5 elements you cannot insert anything beyond the fifth element, that is to say you cannot insert in index 6 (you can add that it is an operation that does not specify where you will insert, it is at the end, period). This goes for any list, it’s physical, you can’t put something on index 6 if you only have 5 elements (it goes from index 0 to 4, you can put it on 5 because it’s the same as adding). Insert is an operation to reach the desired element and add a new element there.
Note that creating a list with a number of elements (you may or may not do this) does not guarantee that you will have objects in it, objects can be null, you would have to create elements and initialize them. But if you wish you can only add elements after creating the list. The first one has to be at the end since there are no other elements. At first it works also, you can not insert in the middle for lack of elements. After there is at least one element can already insert in the middle with the add(index, value)
.
That’s what I meant. It doesn’t create elements in sparse indices dynamically.
– Lucas Pletsch