Stacks
Stacks are dynamic sets whose delete
operation removes the most recently inserted element: stacks are last-in, first out (LIFO).
Stacks get their name (and or inspiration) from spring-loaded stacks of plates found in cafeterias.
Stacks have a top
attribute, which is the index of the most recently inserted element, and a size
attribute, which specifies the maximum size of the underlying array. When top
equals zero the stack is empty.
struct Stack {
int size, top;
int array[STACK_SIZE];
};
bool stack_empty(struct Stack s) {
return (s.top == 0);
}
int push(struct Stack s, int x) {
if (s.top == s.size)
return 0;
else {
s.array[++s.top] = x;
return 1;
}
}
int pop(struct Stack s) {
if (stack_empty(s))
return 0; // Or otherwise signal an error
else
return s.array[s.top--];
}