Stack Inverse Explained
Stack Inverse Explained
h>
#include <stdlib.h>
#include <string.h>
// Function prototypes
void push(struct Stack *s, char c);
char pop(struct Stack *s);
void reverseString(char *str);
int main() {
struct Stack stack;
stack.top = -1; // Initialize stack top
char str[MAX_SIZE];
printf("Enter a string: ");
fgets(str, MAX_SIZE, stdin);
return 0;
}
This C program takes a string as input from the user, reverses the string using a stack, and then prints the
reversed string.
1. **Include necessary header files:** The program includes `stdio.h`, `stdlib.h`, and `string.h` for standard
input/output operations, dynamic memory allocation, and string manipulation functions respectively.
2. **Define constants:** The program defines a constant `MAX_SIZE` to specify the maximum size of the
stack and the input string.
3. **Define the stack structure:** The program defines a stack structure using a C struct. The stack
contains two members: `top` (to track the top of the stack) and `items` (an array to store the stack
elements).
4. **Function prototypes:** The program declares prototypes for three functions: `push`, `pop`, and
`reverseString`.
5. **Main function:**
- Declares a stack variable `stack` and initializes its top to -1.
- Declares a character array `str` to store the user input string.
- Reads a string from the user using `fgets` and removes the newline character at the end of the string.
- Iterates over each character of the input string and pushes it onto the stack using the `push` function.
- Prints the reversed string by popping each character from the stack.
6. **Push function:**
- Takes a pointer to a stack (`struct Stack *s`) and a character `c` as arguments.
- Checks if the stack is full (top equals `MAX_SIZE - 1`) and prints "Stack Overflow" message if so.
- Otherwise, increments the top of the stack and adds the character `c` to the stack.
7. **Pop function:**
- Takes a pointer to a stack (`struct Stack *s`) as an argument.
- Checks if the stack is empty (top equals -1) and prints "Stack Underflow" message if so.
- Otherwise, decrements the top of the stack and returns the character at that position.