In: Computer Science
C++ ONLY -- PRACTICE ASSIGNMENT
We are given a code (Driver.cpp) and asked to create a file (StringStack.h) and turn it in.
What should the code for StringStack.h look like based on the instructions below?
6. Test your stack class using the Driver.cpp file provided for you.
GIVEN DRIVER.CPP FILE:
#include <iostream>
#include "StringStack.h"
using namespace std;
int main()
{
// Define a StringStack object.
StringStack stack;
string animal, lastAnimal;
//get input from user and push to the stack
cout << "\n\nWhat did the old lady eat first? ";
getline(cin, animal);
stack.push(animal);
for(int x=0; x < 6; x++)
{
cout << "\nWhat did she eat next? ";
getline(cin, animal);
stack.push(animal);
}
cout << "\nWhat did she eat last? ";
getline(cin, animal);
stack.push(animal);
//start popping from stack and print results
lastAnimal = stack.pop();
animal = stack.pop();
cout << "\n\nShe swallowed the " << animal << " to catch the ";
animal = stack.pop();
cout << animal << ",\nShe swallowed the " << animal << " to catch the ";
animal = stack.pop();
cout << animal << ",\nShe swallowed the " << animal << " to catch the ";
animal = stack.pop();
cout << animal << ",\nShe swallowed the " << animal << " to catch the ";
animal = stack.pop();
cout << animal << ",\nShe swallowed the " << animal << " to catch the ";
animal = stack.pop();
cout << animal << "\nThat wriggled and jiggled and tickled inside her!\n";
cout << "She swallowed the " << animal << " to catch the ";
animal = stack.pop();
cout << animal << ";\nI don\'t know why she swallowed a " << animal;
cout << " - Perhaps she\'ll die!\n\n";
cout << "There was an old lady who swallowed a " << lastAnimal;
cout << ";\n...She\'s dead, of course!\n\n";
return 0;
}
Code to be pasted in stringStack.h
#pragma once
#include"string"
using namespace std;
class StringStack
{
private:
struct ListNode
{
string str;
ListNode *next;
};
ListNode *headPtr;
public:
StringStack()
{
headPtr = NULL;
}
void push(string inp)
{
ListNode *temp = new ListNode; /*create a node of type list node and initialize its str*/
temp->str = inp;
temp->next = headPtr; /* insert at beginning of list*/
headPtr = temp;
}
string pop()
{
if (headPtr == NULL) /* if stack is empty return empty string*/
{
return "";
}
ListNode * temp = headPtr;
headPtr = headPtr->next; /* advance headptr to next node to delete the first node*/
string tempStr = temp->str; /* store string in node to tempStr. It is done to return it*/
delete temp; /* release memory using delete*/
return tempStr;
}
};