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

Part A: Write a template class of the stack data structure. Part B: Use the temp

ID: 3695658 • Letter: P

Question

Part A: Write a template class of the stack data structure.

Part B: Use the template class in a function that checks whether a given string is a palindrome.

Steps to do that can be:

Create 2 stack objects.

push the first and last characters of the string in the two different stacks.

Keep doing this until you have either 0 or 1 characters left

Then pop one character out from each stack and compare them. If they dont match, print "Not a palindrome" and exit. If both stacks are empty in the end, print "Palindrome found" and exit.

Part C:

Input a string and print its reverse.

Push each character of the string into a stack.

Pop and print each character until the stack is empty

Explanation / Answer

There are two files Stack.h and Stack.cpp

Stack.h

#ifndef STACK_H
#define STACK_H
#include <iostream>
#include <string>
using namespace std;
class Stack
{
  
   private:
       char *stackArray;
       int stackSize;
       int top;
   public:
      
       //constructor
       Stack(int);
       //frees dynamically allocated memory
       ~Stack();
       void push(char);
       char pop();
       bool isEmpty() const;

};
#endif

Stack.cpp

#include "Stack.h"
#include <iostream>
#include <string>
#include <cstring>

Stack::Stack(int len)
{
    stackArray = new char[len];
    stackSize = len;
    top = -1;
}

Stack::~Stack()
{
delete [] stackArray;
}

void Stack::push(char str)
{
    top++;
    stackArray[top] = str;

}

char Stack::pop()
{
    char s =' ';
    if(isEmpty())
    {
        cout <<"No string ";
    } else {
        s= stackArray[top--];
    }
    return s;
}

bool Stack::isEmpty() const
{
    bool status;
    if(top == -1)
        status = true;
    else
        status = false;
  
    return status;
}

using namespace std;
int main()
{
   cout << "Enter a word: ";

   string word;
   cin >> word;

   Stack st(100);
   char c,d;
   for ( int i=0 ;i<word.size(); i++ ){
        c=word.at(i);
       st.push(c);
   }

   bool is_palindrome = true;

   int i=0;
   while(i<word.size()){
        c=word.at(i);
        d = st.pop();
        if(c!=d){
            is_palindrome = false;
            break;
        }
        i++;
   }

   cout << "Word "" << word << "" is "
             << ( is_palindrome ? "" : "not " )
             << "a palindrome."
             << endl;
}