Method 1
#include <stdio.h>
#include <string.h>
#define MAX 100 // Define maximum size of the stack
int top = -1;
char stack[MAX]; // Stack array
// push function
void push(char c) {
if (top < MAX - 1) {
stack[++top] = c;
} else {
printf("Stack overflow\n");
}
}
// pop function (returns character)
char pop() {
if (top >= 0) {
return stack[top--];
}
return '\0'; // return null character if stack empty
}
// Peek function (see top element without removing)
char peek() {
if (top >= 0) {
return stack[top];
}
return '\0';
}
// Check if stack is empty
int isEmpty() {
return (top == -1); // returns 1 if empty, 0 otherwise
}
int main() {
char str[MAX];
// Input the string
printf("Enter string: ");
scanf("%s", str);
int len = strlen(str);
// Push each character of the string onto the stack
for (int i = 0; i < len; i++) {
push(str[i]);
}
// Pop characters to reverse the string
printf("Reversed string: ");
while (!isEmpty()) {
printf("%c", pop());
}
printf("\n");
return 0;
}
#include <stdio.h>
#include <string.h>
#define max 100 // Define maximum size of the stack
int top = -1, stack[max]; // Initialize top and the stack
void push(char x) {
// Push (Inserting Element in stack) operation
if (top == max - 1) {
printf("Stack overflow\n");
} else {
stack[++top] = x; // Push the character onto the stack
}
}
void pop() {
// Pop (Removing element from stack)
if (top == -1) { // Check if stack is empty
printf("Stack underflow\n");
} else {
printf("%c", stack[top--]); // Print and remove the top character
}
}
int main() {
char str[max]; // Array to store the string
// Input the string
printf("Enter string: ");
scanf("%s", str); // Read string input
int len = strlen(str); // Get the length of the string
int i;
// Push each character of the string onto the stack
for (i = 0; i < len; i++) {
push(str[i]);
}
// Pop characters from the stack to reverse the string
printf("Reversed string: ");
for (i = 0; i < len; i++) {
pop(); // Call pop to print each character in reverse
}
printf("\n");
return 0;
}