Skip to content

Implementing Stacks: Array

Another method we could explore for implementing a stack would be the array implementation, the decision between linked lists and arrays will be an important discussion point to consider when looking at requirements.

  • Use array s[] to store N items on a stack
  • push(): add new item at s[N]
  • pop(): remove item from s[N-1]
tobeornottobenullnullnullnull
0123456789
Defect : Stack overflows when N exceeds capacity - Stack has a certain capacity that needs to be declared ahead of time. This is a fundamental problem of arrays.
public class FixedCapacityStackOfStrings{
private String[] s;
private int N = 0;
public FixedCapacityOfStrings(in capacity)
{ s = new String[capacity]; }
public boolean isEmpty()
{ return N == 0; }
public void push(String item)
{ s[N++] = item; }
public void pop()
{ return s[--N]; }
}