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.
Array Implementation of a Stack
Section titled “Array Implementation of a Stack”- Use array
s[]
to storeN
items on a stack - push(): add new item at
s[N]
- pop(): remove item from
s[N-1]
to | be | or | not | to | be | null | null | null | null |
---|---|---|---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
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. |
Full Implementation using Array
Section titled “Full Implementation using Array”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]; }}