Stacks
Stacks
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle,
meaning the last element added to the stack is the first to be removed.
Basic Operations:
o Push: Adds an element to the top of the stack.
o Pop: Removes the top element from the stack.
#include <stdio.h>
int stack[MAX];
if (top == MAX - 1) {
printf("Stack Overflow!\n");
} else {
stack[++top] = value;
void pop() {
if (top == -1) {
printf("Stack Underflow!\n");
} else {
// Main function
int main() {
return 0;
o/p:
Stack Underflow!
operations.(10M)
operations.(10M)
Algorithms
1. Push Operation:
Algorithms:
if top == MAX - 1:
Exit
top = top + 1
stack[top] = value
2. Pop Operation:
Input: None.
Output: Element removed from the top of the stack.
Steps:
1. Check if the stack is empty (i.e., top == -1).
2. If empty, print "Stack Underflow" and exit.
3. Otherwise, retrieve the element at stack[top], decrement top, and return the
value.
Algorithms:
Pop(stack, top):
if top == -1:
Exit
value = stack[top]
top = top - 1
3. Display Operation:
Input: None.
Output: Prints all elements of the stack from top to bottom.
Steps:
1. Check if the stack is empty (i.e., top == -1).
2. If empty, print "The stack is empty."
3. Otherwise, iterate from top to 0 and print each element.
Display(stack, top):
if top == -1:
Exit
for i = top to 0:
Print stack[i]
Principle of Operation:
Stack Underflow occurs when a pop operation is attempted on an empty stack. Since there
are no elements to remove, it results in an error condition indicating that the stack is empty.
1. Check for Overflow: Ensure that the stack is not full (i.e., top != MAX - 1).
2. Increment the Top: Increase the top pointer to the next position.
3. Insert the Element: Place the new element at the position pointed to by top.
1. Check for Underflow: Ensure that the stack is not empty (i.e., top != -1).
2. Retrieve the Element: Access and store the element at the position pointed to by top.
3. Decrement the Top: Decrease the top pointer to the previous position.
algorithms.(5M)
Algorithms
1. Push Operation:
Algorithms:
if top == MAX - 1:
Print "Stack Overflow"
Exit
top = top + 1
stack[top] = value
2. Pop Operation:
Input: None.
Output: Element removed from the top of the stack.
Steps:
1. Check if the stack is empty (i.e., top == -1).
2. If empty, print "Stack Underflow" and exit.
3. Otherwise, retrieve the element at stack[top], decrement top, and return the
value.
Algorithms:
Pop(stack, top):
if top == -1:
Exit
value = stack[top]
top = top - 1
#include <stdio.h>
#define MAX 5
int stack[MAX];
stack[++top] = value;
} else {
printf("Stack Overflow\n");
// Pop operation
void pop() {
if (top >= 0) {
} else {
printf("Stack Underflow\n");
// Display operation
void display() {
if (top >= 0) {
printf("\n");
} else {
printf("Stack is empty\n");
}
// Main function
int main() {
push(10);
push(20);
display();
pop();
display();
pop();
return 0;
o/p:
10 pushed to stack
20 pushed to stack
20 10
10 pushed to stack
Stack is empty