There are several ways to program a stack.
Using an Array
One is in using an array. Here a stack with a max size of the array is created, and an index is used to track the latest element. It can, of course, run out of space, which is known as a stack overflow. This error occurs when an additional item is attempted to be added to a full stack.
Linked List
Another method is to use a linked list. Using some basic pseudocode you can see how a linked list stack would work.
function boolean isEmpty() {
return stack == null;
}
function void push(Object item) {
item.nextItem = stack;
stack = item;
}
function Object pop() {
Object toBeReturned = null;
if(!this.isEmpty()) {
toBeReturned = stack;
stack = toBeReturned.nextItem;
}
return toBeReturned;
}
function Object top() {
Object toBeReturned = null;
if(!this.isEmpty()) {
toBeReturned = stack;
// notice no removal of the item
}
return toBeReturned;
}
Programming the Stack was originally found on Access 2 Learn