private void checkBounds(int n)
{
if (n < 0 || n >= currentSize) { throw new IndexOutOfBoundsException(); }
}
public Object get(int pos)
{
checkBounds(pos);
return buffer[pos];
}public Object remove(int pos)
{
checkBounds(pos);
Object removed = buffer[pos];
for (int i = pos + 1; i < currentSize; i++) { buffer[i - 1] = buffer[i]; }
currentSize--;
return removed;
}Consider the removeLast operation of an ArrayList, implemented as
public Object removeLast() { return remove(size() - 1); }
Which of the following is true about this operaton?
private void growBufferIfNecessary()
{
if (currentSize == buffer.length)
{
Object[] newBuffer = new Object[2 * buffer.length];
for (int i = 0; i < buffer.length; i++) { newBuffer[i] = buffer[i]; }
buffer = newBuffer;
}
}add (i.e. addLast)
add| Array List | Doubly Linked List | Singly Linked List | |
| Add at end | O(1)+ | O(1) | O(1) |
| Remove at end | O(1)+ | O(1) | O(n) |
| Add at head | O(n) | O(1) | O(1) |
| Remove at head | O(n) | O(1) | O(1) |
| Add in middle* | O(n) | O(1) | O(1) |
| Remove in middle* | O(n) | O(1) | O(1) |
*Provided you are already there (with an integer index or iterator)
You want to add a zero directly in the middle of a sequence of integers (or replace the middle element with a zero if the sequence has odd length). For example,
1 2 3 4 5 6 → 1 2 3 0 4 5 6
1 2 3 4 5 6 7 →1 2 3 0 5 6 7
Which data structure should you use for maximum efficiency