Data Structures: Stacks
Data Structures: Stacks
Stacks
DATA
STRUCTURES
STACK IMPLEMENTATIONS
• Linked Implementation
• Array-Based Stack Implementation
ARRAY-BASED STACK IMPLEMENTATION
public ArrayStack()
{
this(DEFAULT_CAPACITY);
} // end default constructor
// 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
• 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