Professional Documents
Culture Documents
DSU Vol 2 Notes (3rd Chapter)
DSU Vol 2 Notes (3rd Chapter)
Definition of Stack -:
A stack is a fundamental data structure that follows the Last In, First Out
(LIFO) principle. In a stack, the last element added is the first one to be
removed. Think of it like a stack of plates where you add or remove plates from
the top.
1. LIFO (Last In, First Out): The last element added is the first one to be
removed.
2. Operations:
3. Implementation:
Stack Operations
Push Operation
3. Assign the new element to the position indicated by the top pointer.
stack[top] = newElement;`
Initial Stack: [1, 2, 3]
Push 4:
Pop Operation:
The pop operation removes the element from the top of the stack.
poppedElement = stack[top];`
Pop:
Popped Element: 4
Example Code (in C):
#define MAX_SIZE 10
int stack[MAX_SIZE];
int top = -1;
// Push operation
void push(int newElement) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow. Cannot push %d.\n", newElement);
return;
}
top = top + 1;
stack[top] = newElement;
}
// Pop operation
int pop() {
if (top == -1) {
printf("Stack Underflow. Cannot pop.\n");
return -1; // Or some sentinel value indicating underflow
}
#include <stdio.h>
#define MAX_SIZE 10
// Stack structure
struct Stack {
int arr[MAX_SIZE];
int top;
};
stack->arr[++stack->top] = element;
printf("Element %d pushed successfully.\n", element);
}
int main() {
struct Stack stack;
initialize(&stack);
do {
printf("\nStack Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(&stack, element);
break;
case 2:
pop(&stack);
break;
case 3:
display(&stack);
break;
case 4:
printf("Exiting the program. Goodbye!\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);
return 0;
}
Applications of Stack
2. Expression Evaluation:
Stacks are employed to evaluate expressions, especially infix to postfix or
infix to prefix conversions. The stack helps in maintaining the order of
operations.
Many software applications, like text editors or graphic design tools, use
stacks to implement undo functionalities. Each operation is pushed onto
the stack, and undo pops the last operation.
4. Backtracking Algorithms:
5. Browser History:
The "Back" button in web browsers uses a stack to keep track of visited
pages. Each time a new page is visited, it is pushed onto the stack, and
going back pops the last visited page.
6. Parsing in Compilers:
Stacks play a vital role in syntax analysis phase during compilation. They
are used to store and manage grammar rules and symbols for parsing.
7. Memory Management:
8. Balancing Symbols:
Stacks are employed to check the balance of symbols like parentheses,
braces, and brackets in expressions. Each opening symbol is pushed onto
the stack, and a closing symbol pops it.
9. Task Scheduling: