In: Computer Science
****C++, put both of them in to one main method, make sure to start with main class, if I get a screenshot of the output as well.
thank you
(1) A palindrome is a string that reads the same forwards as backwards. Using only a fixed number of stacks and queues, the stack and queue ADT functions, and a fixed number of int and char variables, write an algorithm to determine if a string is a palindrome. Assume that the string is read from standard input one character at a time. The algorithm should output true or false as appropriate
(2) Let Q be a non-empty queue, and let S be an empty stack. Using only the stack and queue ADT functions and a single element variable X, write an algorithm to reverse the order of the elements in Q.
Algorithm:
Please refer to the comments of the program for more clarity.
#include<bits/stdc++.h>
using namespace std;
int main()
{
// Initialization of the variables
cout << "Enter the string: ";
string s;
// Taking the string as input
cin >> s;
// Declaring stack and queue to check palindrome
stack<char> s1;
queue<char> q1;
// Declaring stack and queue to find the reverse of the given string.
queue<char> Q;
stack<char> S;
// Inserting the input string to the stack and queue
for(int i=0; i<s.length(); i++)
{
s1.push(s[i]);
q1.push(s[i]);
Q.push(s[i]);
}
// Initializing the boolean to store whether the given string is palindrome or not
bool isStringPalindrome = false;
// Checking for the palindrome
int sameCounter = 0;
for(int i=0; i< s.length(); i++)
{
if(s1.top() == q1.front())
{
// Increasing the counter when characters from the starting and from reverse are the same
sameCounter++;
}
s1.pop();
q1.pop();
}
// When all the characters are the same then sameCounter will be equal to the length of the string
if(sameCounter == s.length())
isStringPalindrome = true;
// When isStringPalindrome == 1, it means string is palindrome and when isStringPalindrome == 0, string will not be palindrome
cout << "Is given string palindrome: ";
if(isStringPalindrome == 1)
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
// Question - 2
// Reversing the given string
for(int i=0; i<s.length(); i++)
{
S.push(Q.front());
Q.pop();
}
// Finally, printing the reverse of the input string
cout << "Reverse of the given string: ";
for(int i=0; i<s.length(); i++)
{
cout << S.top();
S.pop();
}
return 0;
}
Sample Input-Output/CodeRun -1:
Sample Input-Output/CodeRun -2:
Repl screenshot:
Please let me know in the comments in case of any confusion. Also, please upvote if you like.