Prog - 3 Stack Op
Prog - 3 Stack Op
Prog - 3 Stack Op
Support the program with appropriate functions for each of the above operations
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int stack[MAX];
int top = -1;
int pop()
{
if (top == -1)
{
printf("Stack Underflow! Cannot pop from an empty stack.\n");
return -1;
}
else
{
int ele = stack[top--];
return ele;
}
}
int isPalindrome()
{
int i, j;
for (i = top, j = 0; i >= j; i--, j++)
{
if (stack[i] != stack[j])
{
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}
void displayStack()
{
if (top == -1)
{
printf("Stack is empty.\n");
} else
{
printf("Stack elements: ");
for (int i = top; i >=0; i--)
printf("%d\t", stack[i]);
printf("\n");
}
}
int main()
{
int choice, element;
do {
printf("\n----- Menu -----\n");
printf("1. Push an Element\n");
printf("2. Pop an Element\n");
printf("3. Check Palindrome\n");
printf("4. Display Stack Status\n");
printf("5. Exit");
printf("\n----------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(element);
break;
case 2:
int val=pop();
printf("%d popped from the stack.\n", val);
break;
case 3:
if (isPalindrome())
printf("The stack is a palindrome.\n");
else
printf("The stack is not a palindrome.\n");
break;
case 4:
displayStack();
break;
case 5:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please enter a valid option.\n");
}
} while (choice != 5);
return 0;
}
Output:
----- Menu -----
1. Push an Element
2. Pop an Element
3. Check Palindrome
4. Display Stack Status
5. Exit
----------------
Enter your choice: 1
Enter the element to push: 12
12 pushed onto the stack.