#include #include const int MAXCHARS = 30; const int TRUE = 1; const int FALSE = 0; // class declaration // preconditions: requires that MAXCHARS, the maximum size of a name, be defined // : requires that TRUE be defined as a nonzero integer // : requires that FALSE be defined as 0 class Stack { private: struct NameRec { char name[MAXCHARS]; NameRec *prioraddr; }; NameRec *top; // top-of-stack pointer public: Stack(); // constructor void push(char *); char *pop(); int isempty(); }; // implementation section Stack::Stack() // constructor { top = NULL; } void Stack::push(char *newname) { NameRec *newAddr; // a pointer to a NameRec newAddr = new (NameRec); if (newAddr == NULL) { cout <<"\nNo more storage allocation space" << "\nThe last name has not been entered on the stack" << endl; } else { strcpy(newAddr->name, newname); // store the name newAddr->prioraddr = top; // store the address top = newAddr; // update top } return; } char *Stack::pop() // return a pointer to a name { NameRec *tempAaddr; char name[MAXCHARS]; strcpy(name,top->name); // retrieve the name from top-of-stack tempAddr = top->prioraddr; // retrieve prior address delete(top); // free record's memory space top = tempAddr; // update the top-of-stack pointer return name; } int Stack::isempty() { if (top == NULL) return TRUE; else return FALSE; } int main() { char newname[MAXCHARS]; Stack namestack; // define a Stack object cout << "Enter as many names as you wish, one per line" << "\nTo stop entering names, enter a single x\n"; while (1) { cout << "Enter a name: "; cin.getline(newname,MAXCHARS); if (strcmp(newname,"x") == 0) break; else namestack.push(newname); } // pop and display names from the stack cout << "\nThe names popped from the stack are:\n"; while (!namestack.isempty()) { strcpy(newname,namestack.pop()); cout << newname << endl; } return 0; }