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

Write a C++ program that uses the queue and stack containers to read string of c

ID: 3565057 • Letter: W

Question

Write a C++ program that uses the queue and stack containers to read string of characters,
pushing each character onto a stack as it is read and simultaneously adding it to a queue. When
the end of the string is encountered, the program should use the basic stack and queue
operations to determine if the string is a palindrome.
Requirements:
1. Input string must be read at keyboard, with proper prompting message.
2. When finishing testing one string, the program must empty the stack and the queue
and loop back to read the next string. The looping should be terminated upon reading
string

Explanation / Answer

#include <iostream>
#include <stack>
#include <queue>
#include <string>

using namespace std;

bool operator==(const stack<char>&, const queue<char>&);
bool operator!=(const stack<char>&, const queue<char>&);

int main(int argc, char *argv[]) {
stack<char> *s;
queue<char> *q;
string input;
string::iterator i;

while (true) {
s = new stack<char>;
q = new queue<char>;

cout << "> ";
getline(cin,input);
for (i = input.begin(); i != input.end(); i++) {
s->push(*i);
q->push(*i);
}
cout << input << " is ";
if (*s != *q) {
cout << "not ";
}
cout << "a palindrome." << endl;

delete s;
delete q;
}

return 0;
}

bool operator==(const stack<char> &s1, const queue<char> &q1) {
bool eq = true;
stack<char> s = s1;
queue<char> q = q1;

if (s.size() == q.size()) {
while ((s.empty() == false) && (eq == true)) {
eq = (s.top() == q.front());
s.pop();
q.pop();
}
} else {
eq = false;
}
return eq;
}

bool operator!=(const stack<char> &s, const queue<char> &q) {
return !(s == q);
}

#if 0

Sample run:

> hello, world
hello, world is not a palindrome.
> abba
abba is a palindrome.
> 1234321
1234321 is a palindrome.
>

Hope you understand. Feel free to ask any doubts. Have a nice day :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote