Answer to Question #276861 in C for tom

Question #276861

Write a program that reads in a sequence of characters and prints them in reverse order (Use a stack).


1
Expert's answer
2021-12-07T20:57:46-0500
#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;
}

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