CSC211 Data Structures and Algorithms

Data Structures and AlgorithmsTU Board 2080

Explain push and pop operations of stack. What are different applications of stack?

5

Answer

A stack is a linear data structure where insertion and deletion happen at one end, called the top. It follows LIFO (last in, first out).

PUSH (insert)

  1. If top == MAX - 1, report stack overflow and stop.
  2. Otherwise increase top by 1.
  3. Store the item at stack[top].

POP (delete)

  1. If top == -1, report stack underflow and stop.
  2. Otherwise take the item at stack[top].
  3. Decrease top by 1 and return the item.
#define MAX 10
int stack[MAX], top = -1;

void push(int x) {
    if (top == MAX - 1) { printf("Overflow\n"); return; }
    stack[++top] = x;
}

int pop(void) {
    if (top == -1) { printf("Underflow\n"); return -1; }
    return stack[top--];
}

For example, after push(5), push(8), push(3) the stack is [5, 8, 3] with 3 on top. pop() returns 3 and leaves [5, 8].

Applications of stack

  • Function calls and recursion: return addresses and local variables are kept on the call stack.
  • Expression conversion and evaluation: infix to postfix/prefix, and evaluating postfix expressions.
  • Balanced parentheses checking in compilers and editors.
  • Undo/redo in editors and the back button in browsers.
  • Backtracking: maze solving, depth-first search.
  • Reversing a string or a list.

Discussion

Loading…

More Data Structures and Algorithms questions

All Data Structures and Algorithms old questions