Lecture 2
Stacks
DATA
STRUCTURES
STACK IMPLEMENTATIONS
• Linked Implementation
• Array-Based Stack Implementation
ARRAY-BASED STACK IMPLEMENTATION
• Each operation involves top of stack
• push
• pop
• peek
• End of the array easiest to access
• Let this be top of stack
• Let first entry be bottom of stack
ARRAY-BASED STACK IMPLEMENTATION
• FIGURE 6-4 Two array representations of a stack
ARRAY-BASED STACK IMPLEMENTATION
ARRAY-BASED STACK IMPLEMENTATION
ARRAY-BASED STACK IMPLEMENTATION
PRINT THE CONTENT OF A STACK WITHOUT CHANGING IT
ARRAY-BASED STACK IMPLEMENTATION
/** A class of stacks whose entries are stored in an array. */
public final class ArrayStack<T> implements StackInterface<T>
{
private T[] stack; // Array of stack entries
private int topIndex; // Index of top entry
private boolean integrityOK = false;
private static final int DEFAULT_CAPACITY = 50;
private static final int MAX_CAPACITY = 10000;
public ArrayStack()
{
this(DEFAULT_CAPACITY);
} // end default constructor
public ArrayStack(int initialCapacity)
{
integrityOK = false;
checkCapacity(initialCapacity);
// The cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempStack = (T[])new Object[initialCapacity];
stack = tempStack;
topIndex = -1;
integrityOK = true;
} // end constructor
// < Implementations of the stack operations go here. >
} // end ArrayStack
• LISTING 6-2 An outline of an array-based implementation of the ADT stack
ARRAY-BASED STACK IMPLEMENTATION
• Adding to the top.
public void push(T newEntry)
{
checkInyegrity();
ensureCapacity();
stack[topIndex + 1] = newEntry;
topIndex++;
} // end push
private void ensureCapacity()
{
if (topIndex >= [Link] - 1) // If array is full, double its size
{
int newLength = 2 * [Link];
checkCapacity(newLength);
stack = [Link](stack, newLength);
} // end if
} // end ensureCapacity
ARRAY-BASED STACK IMPLEMENTATION
• FIGURE 6-5 An array-based stack after its top entry is removed in two different ways
ARRAY-BASED STACK IMPLEMENTATION
public T peek()
{
checkIntegrity();
if (isEmpty())
throw new EmptyStackException();
else
return stack[topIndex];
} // end peek
public T pop()
{
checkIntegrity();
if (isEmpty())
throw new EmptyStackException();
else
{
T top = stack[topIndex];
stack[topIndex] = null;
topIndex--;
return top;
} // end if
} // end pop
• Retrieving the top, operation is O(1)