Write a program that reads in a sequence of characters and prints them in reverse order (Use a stack).
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Stack {
size_t size;
size_t top;
char* data;
} Stack;
Stack* initStack(size_t size) {
Stack* s = (Stack *) malloc(sizeof(Stack));
s->size = size;
s->top = 0;
s->data = (char*) malloc(size*sizeof(char));
return s;
}
void freeStack(Stack* s) {
free(s->data);
free(s);
}
void push(Stack* s, char ch) {
if (s->top < s->size) {
s->data[s->top++] = ch;
}
}
char pop(Stack* s) {
if (s->top > 0) {
return s->data[--s->top];
}
else {
return '\0';
}
}
bool isEmpty(Stack* s) {
return s->top == 0;
}
int main() {
Stack* stack;
char buf[1024];
char *p;
char ch;
stack = initStack(1024);
scanf("%s", &buf[0]);
p = buf;
while (*p) {
push(stack, *p);
++p;
}
printf("\n");
while (!isEmpty(stack)) {
ch = pop(stack);
printf("%c", ch);
}
printf("\n");
freeStack(stack);
return 0;
}
Comments
Leave a comment