Answer to Question #265144 in C for Samzzy

Question #265144

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.

1
Expert's answer
2021-11-12T17:31:34-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS