-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringReversalUsingStack.c
More file actions
80 lines (64 loc) · 2.03 KB
/
StringReversalUsingStack.c
File metadata and controls
80 lines (64 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a stack structure to hold the characters
#define MAX 100 // Maximum size of the stack
struct Stack {
char arr[MAX]; // Array to hold the characters
int top; // Points to the top of the stack
};
// Function to initialize the stack
void initStack(struct Stack* stack) {
stack->top = -1; // Set the top to -1 to indicate that the stack is empty
}
// Function to check if the stack is full
int isFull(struct Stack* stack) {
return stack->top == MAX - 1;
}
// Function to check if the stack is empty
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// Function to push an element onto the stack
void push(struct Stack* stack, char value) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->arr[++(stack->top)] = value; // Increment top and insert the value
}
// Function to pop an element from the stack
char pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1; // Return -1 if the stack is empty
}
return stack->arr[(stack->top)--]; // Return the top value and decrement top
}
// Function to reverse a string using a stack
void reverseString(char* str) {
struct Stack stack;
initStack(&stack); // Initialize the stack
// Push all characters of the string onto the stack
for (int i = 0; str[i] != '\0'; i++) {
push(&stack, str[i]);
}
// Pop characters from the stack to reverse the string
int i = 0;
while (!isEmpty(&stack)) {
str[i++] = pop(&stack); // Replace characters in the original string
}
}
int main() {
char str[MAX];
// Input the string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove the newline character from the string if present
str[strcspn(str, "\n")] = 0;
// Reverse the string using the stack
reverseString(str);
// Output the reversed string
printf("Reversed string: %s\n", str);
return 0;
}