Skip to main content

Stack definition and basic operations

Short answer

A stack is a linear LIFO structure (e.g., pile of plates). Push inserts at top, pop removes top, peek returns top. Algorithms: push increments top and stores x; pop returns top element and decrements top; overflow/underflow checks ensure bounds.

Define Stack with suitable example. Write down the algorithm for the basic operation that can be performed over the stack.

A stack is a linear data structure in which insertion (push) and deletion (pop) take place only at one end, called the top. The last element inserted is the first one removed, so it follows LIFO (Last In First Out).

Example: a pile of plates. Push 10, 20, 30 gives stack (bottom to top) 10 20 30; pop returns 30, leaving 10 20.

Algorithms (array S[0..MAX-1], top = -1 initially)

PUSH(S, x)
1. if top == MAX - 1:  print "Stack overflow"; exit
2. top = top + 1
3. S[top] = x

POP(S)
1. if top == -1:  print "Stack underflow"; exit
2. x = S[top]
3. top = top - 1
4. return x

PEEK(S)                    /* stacktop */
1. if top == -1:  print "Stack empty"; exit
2. return S[top]

EMPTY(S):  return (top == -1)
FULL(S):   return (top == MAX - 1)

C code

#define MAX 5
int s[MAX], top = -1;
void push(int x) { if (top == MAX-1) printf("Stack overflow\n"); else s[++top] = x; }
int  pop(void)   { if (top == -1) { printf("Stack underflow\n"); return -1; } return s[top--]; }

Every operation takes O(1) time.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 2 questions →