// lifo.h -- Stack of characters (dynamic storage) class Lifo { struct node{ node *next; char value; }; node * next; // whence we pop public: // create and initialize a lifo Lifo(); // push a new value into an existing lifo void push(char who); // pop a value from a lifo char pop(); // check if a lifo is empty int isempty(); }; // lifo.cpp -- Stack of characters (dynamic storage) #include "lifo.h" #define NULL 0 // Create and initialize a lifo // It returns a lifo whose next field is null and // whose count is 0 Lifo::Lifo() { next = NULL; } // push a new value into an existing lifo void Lifo::push(char who) { node *a = new node; a->next = next; a->value = who; next = a; } // pop a value from a lifo char Lifo::pop() { node *headNode; char who; if (next != NULL) { headNode = next; next = next->next; who = headNode->value; delete headNode; return who; } return '\0'; // You should never execute this // statement (i.e. do not pop // an empty stack) } // check if a lifo is empty int Lifo::isempty() { return (next == NULL); } // main.cpp -- Driver for lifo of characters. // Verify that a formula consisting of appropriately // nested strings formed with the parentheses // {,},[,],(,) is well-formed. #include #include "lifo.h" using namespace std; // Return true iff c1 and c2 are matching parentheses int matching(char c1, char c2){ if (((c1 == '(') && (c2 == ')')) || ((c1 == '[') && (c2 == ']')) || ((c1 == '{') && (c2 == '}'))) return 1; else return 0; } enum {LINEMAX=256}; void main(void) { char line[LINEMAX]; int lcv; Lifo stack; char c1; cout << "Enter a well formed string formed with {,},[,],(,): "; cin.getline(line, LINEMAX); lcv = 0; while((c1 = line[lcv++]) != '\0'){ if (isspace(c1)) ; else if ((c1 == '{') || (c1 == '[') || (c1 == '(')) stack.push(c1); else if ((c1 == '}') || (c1 == ']') || (c1 == ')')) { if (stack.isempty()) { cout << "Too many right parentheses" << endl; return; } else { if (!matching(stack.pop(), c1)){ cout << "The string has non-matching parentheses" << endl; return; } } }else{ cout << "The string contains an illegal character" << endl; return; } } if (stack.isempty()) cout << "The string is well formed" << endl; else cout << "Too many left parentheses" << endl; }