Write a C program to reverse each word of the string by using static and dynamic Implementation of stack. Example: Input – This is an input string .Output – sihTsinatupnignirts
Static Stack Implementation (Using Array)
#include <stdio.h>
#include <string.h>
#define MAX 100
// Stack structure
typedef struct {
char arr[MAX];
int top;
} Stack;
// Initialize stack
void init(Stack *s) {
s->top = -1;
}
// Push operation
void push(Stack *s, char c) {
if (s->top < MAX - 1) {
s->arr[++(s->top)] = c;
}
}
// Pop operation
char pop(Stack *s) {
if (s->top >= 0) {
return s->arr[(s->top)--];
}
return '\0';
}
// Check if stack is empty
int isEmpty(Stack *s) {
return s->top == -1;
}
int main() {
char str[MAX];
Stack s;
init(&s);
printf("Enter a string: ");
fgets(str, MAX, stdin);
for (int i = 0; i < strlen(str); i++) {
if (str[i] != ' ' && str[i] != '\n') {
push(&s, str[i]);
} else {
while (!isEmpty(&s)) {
printf("%c", pop(&s));
}
printf("%c", str[i]);
}
}
// Print remaining characters
while (!isEmpty(&s)) {
printf("%c", pop(&s));
}
return 0;
}
Dynamic Stack Implementation (Using Linked List)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
// Node structure
typedef struct Node {
char data;
struct Node* next;
} Node;
// Push operation
void push(Node** top, char c) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = c;
newNode->next = *top;
*top = newNode;
}
// Pop operation
char pop(Node** top) {
if (*top == NULL)
return '\0';
Node* temp = *top;
char popped = temp->data;
*top = temp->next;
free(temp);
return popped;
}
// Check if empty
int isEmpty(Node* top) {
return top == NULL;
}
int main() {
char str[MAX];
Node* top = NULL;
printf("Enter a string: ");
fgets(str, MAX, stdin);
for (int i = 0; i < strlen(str); i++) {
if (str[i] != ' ' && str[i] != '\n') {
push(&top, str[i]);
} else {
while (!isEmpty(top)) {
printf("%c", pop(&top));
}
printf("%c", str[i]);
}
}
// Print remaining characters
while (!isEmpty(top)) {
printf("%c", pop(&top));
}
return 0;
}
