Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

14. (12 pts) Write a function called reverseString(), which uses a Stack to reve

ID: 3730223 • Letter: 1

Question

14. (12 pts) Write a function called reverseString(), which uses a Stack to reverse a C string (char "). The string that is to be reversed is passed in as a parameter. The function should reverse the characters in the string (i.e. "cat" becomes "tac") and return a pointer to the reversed string. A second string or array should NOT be used to reverse or store the characters. The Stack supports the following member functions: bool push (char c); // adds c to the top of the stack bool pop (char &c;) // removes the character at top of stack and places in // parameter c bool isEmpty : // returns true if stack is empty: false otherwise The function header and Stack object instantiation has been supplied for you below: char reverseString (char pStr) Stack theStack:

Explanation / Answer

Answer: The idea is push the charachers one by one in stack and then pop the character one by one from the stack. It will reverse the string.

char * reverse(char *pstr)

{

    // Create a stack of capacity equal to length of string

    int n = strlen(pstr);

    struct Stack* stack = createStack(n);

    // Push all characters of string to stack

    int i;

    for (i = 0; i < n; i++)

        push(stack, pstr[i]); // as we can say string is array of characters

    // Pop all characters of string and put them back to str

    for (i = 0; i < n; i++)

pstr[i] = pop(stack);

return pstr;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote