Data Structures and AlgorithmsTU Board 2080
Explain push and pop operations of stack. What are different applications of stack?
5Answer
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)
- If
top == MAX - 1, report stack overflow and stop. - Otherwise increase
topby 1. - Store the item at
stack[top].
POP (delete)
- If
top == -1, report stack underflow and stop. - Otherwise take the item at
stack[top]. - Decrease
topby 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
Define circular queue. How queue differ from stack. Write a program to implement linear queue.TU Board 208110What is AVL tree? How heap differ from tree? Construct an AVL tree for data 24,12,8,15,35,30,57,40,45 and 78.TU Board 208110Define list. How can you use linked list to implement stack? Explain circular linked list.TU Board 208110Explain big oh notation in brief. Find big oh of the following function: f(x) = 5x^4 + 9x^2 + 7x + 9.TU Board 20815Convert the infix expression A+(((B C) (D E)+F)/G)$(H I) into post expression using stack.TU Board 20815Write a program to find GCD of two numbers using recursion.TU Board 20815