Sample Program Using a Queue: Finding Palindromes
// this program will read a string and determine whether it is a // palindrome (a string is a palindrome if it is the same forwards and // backwards, ignoring capitalization and punctuation) // // the user is prompted to enter the string in lowercase. the program // reads each character. as the characters are read they are checked, // and if the character is a letter then the character is pushed on a // stack and added to a queue. the stack then contains the reverse of the // original string and the queue contains the original string. these two // strings are compared; if they are equal then the string is a palindrome. #include "stacklst.h" #include "queuelst.h" #includeint main() { Stack chstack; // stack to hold reversed string Queue chqueue; // queue to hold original string char inchar; // character entered by user char stchar; // character popped from stack char qchar; // character removed from queue int ispalindrome; // flag: is the string a palindrome? int ok; // flag: did the stack/queue overflow? // initialize, then read string and create original and reversed // versions using the stack and queue ok = 1; cout << "Enter a line of text (all lowercase)\n"; inchar = cin.get(); while (inchar != '\n' && ok) { if (inchar != ' ') { ok = chstack.push(inchar); ok = chqueue.insert(inchar); inchar = cin.get(); } } // end while // get one character at a time from each string and compare them. if // they ever differ then the string was not a palindrome if (ok) { ispalindrome = 1; while (!chstack.isEmpty() && !chqueue.isEmpty() && ispalindrome) { ok = chstack.pop(stchar); ok = chqueue.del(qchar); if (stchar != qchar) ispalindrome = 0; } // end while // check ispalindrome to find out whether the two strings matched // everywhere if (ispalindrome) cout << "The string is a palindrome\n"; else cout << "The string is not a palindrome\n"; } else cout << "Error: phrase is too long to check\n"; }
Email Me | Office Hours | My Home Page | Department Home | MCC Home Page