Write a program that let's you input a string. The program then should push the characters of the string onto a stack, one by one, and then pop the characters from the stack and display them. This results is displaying the string in reverse order.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
struct Stack
{
int t;
unsigned c;
char* arr;
};
struct Stack* createStack(unsigned c)
{
struct Stack* st = (struct Stack*) malloc(sizeof(struct Stack));
st->c = c;
st->t = -1;
st->arr = (char*) malloc(st->c * sizeof(char));
return st;
}
int isFull(struct Stack* st)
{ return st->t == st->c - 1; }
int isEmpty(struct Stack* st)
{ return st->t == -1; }
void push(struct Stack* st, char i)
{
if (isFull(st))
return;
st->arr[++st->t] = i;
}
char pop(struct Stack* st)
{
if (isEmpty(st))
return INT_MIN;
return st->arr[st->t--];
}
void reverse(char str[])
{
int num = strlen(str);
struct Stack* st = createStack(num);
int i;
for (i = 0; i < num; i++)
push(st, str[i]);
for (i = 0; i < num; i++)
str[i] = pop(st);
}
int main()
{
char str[] = "Hello";
reverse(str);
printf("Reversed string = %s", str);
return 0;
}
Comments
Leave a comment