we are going to share a C program to reverse a string using the stack. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to reverse a string using stack with the output.
1) Define an empty stack.
2) Push all characters of string to stack one by one.
3) Pop all characters from stack and put them back to string one by one.
Here is an example “fwmquiz” will be converted to “ziuqmwf”.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the program.
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 | #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> struct Stack { int top; unsigned capacity; char* array; }; struct Stack* createStack(unsigned capacity) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (char*) malloc(stack->capacity * sizeof(char)); return stack; } int isFull(struct Stack* stack) { return stack->top == stack->capacity - 1; } int isEmpty(struct Stack* stack) { return stack->top == -1; } void push(struct Stack* stack, char item) { if (isFull(stack)) return; stack->array[++stack->top] = item; } char pop(struct Stack* stack) { if (isEmpty(stack)) return INT_MIN; return stack->array[stack->top--]; } void reverse(char str[]) { int n = strlen(str); struct Stack* stack = createStack(n); int i; for (i = 0; i < n; i++) push(stack, str[i]); for (i = 0; i < n; i++) str[i] = pop(stack); } int main() { char str[] = "fwmquiz"; reverse(str); printf("Reversed string is %s", str); return 0; } |
Reversed string is ziuqmwf
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.