Stacks Flashcards
Name the three core stack methods.
Push, pop, and peek.
Fill in the blank:
public interface PureStack<E>{
void \_\_(E item);
\_\_ pop();
E \_\_\_();
boolean \_\_();
int \_\_();
}</E>
push; E; peek; isEmpty; size
Stacks may be implemented using what two data structures?
Arrays and linked lists.
For a array-backed stack, the push, pop, and peek operations have what runtime?
O(1)
For a linked list-backed stack, the push, pop, and peek operations have what runtime?
O(1)
The stack method push() is analogous to what List method?
add()
The stack method peek() is analogous to what List method?
get(size() - 1)
The stack method pop() is analogous to what List method?
remove(size() - 1)
The stack method push() is analogous to what Deque method?
addFirst()
The stack method pop() is analogous to what Deque method?
removeFirst()
The stack method peek() is analogous to what Deque method?
peekFirst()
Define “overflow”.
Trying to push onto a full stack.
Define “underflow”.
Trying to pop on an empty stack.
Write the pop() method for an array-based stack.
@Override
public E pop()
{
if (top == 0) throw new NoSuchElementException();
E ret = data[–top];
data[top] = null;
return ret;
}
Write the push() method for an array-based stack.
@Override
public void push(E item)
{
checkCapacity();
data[top++] = item;
}
/**
* Ensures that the backing array has space to store at least
* one additional element.
*/
private void checkCapacity()
{
if (top == data.length)
{
// create a copy of the data array with double the capacity
data = Arrays.copyOf(data, data.length * 2);
}
}