A stack is a LIFO (last-in, first-out) structure supporting push (insert at top), pop (remove from top), peek/top (read the top without removing it), and isEmpty/isFull. Each is O(1) whether the stack is built on a fixed-size array or on a linked list. The array version keeps a top index and is full when top == capacity-1; a push in that state overflows. The linked-list version pushes and pops at the head, so no traversal is ever needed.
#define MAXSIZE 100
int stackArr[MAXSIZE];
int top = -1;
int isEmpty(void) { return top == -1; }
int isFull(void) { return top == MAXSIZE - 1; }
void push(int x) {
if (isFull()) { /* overflow */ return; }
stackArr[++top] = x;
}
int pop(void) {
if (isEmpty()) { /* underflow */ return -1; } /* -1 is only an illustrative sentinel */
return stackArr[top--];
}
Stacks are used for expression conversion and evaluation, function-call and recursion bookkeeping, parenthesis matching and backtracking. They also answer whether a given output order can be produced from an input order using only push and pop.
In these infix-expression questions ^ means exponentiation. It is NOT C's ^ operator, which is bitwise XOR and has a much lower precedence.
NUMBER OF DISTINCT VALID STACK-PERMUTATION OUTPUTS OF N ELEMENTS
Cn=(n+1)!n!(2n)!=n+11(n2n)
n distinct elements pushed in a fixed order (1, 2, ..., n) through one stack, with pushes and pops interleaved freely. C_n (the nth Catalan number) counts the distinct output sequences: C_1 = 1, C_2 = 2, C_3 = 5, C_4 = 14, C_5 = 42.
Two stacks in one array. Two stacks can share an array of size N without wasting space: stack 1 grows upward from index 0 and stack 2 grows downward from index N-1. Overflow happens only when the whole array is used.
#define N 100
int arr[N];
int top1 = -1;
int top2 = N;
void push1(int x) {
if (top1 + 1 == top2) { /* overflow: array full */ return; }
arr[++top1] = x;
}
void push2(int x) {
if (top1 + 1 == top2) { /* overflow: array full */ return; }
arr[--top2] = x;
}
The array is full exactly when top1 + 1 == top2.