🔄 Day 18: Queues and Stacks
🎯 Goal:
Use a stack and a queue to check whether a string is a palindrome.
📘 Problem Statement:
Write a class with the following methods:
void SendCharacter(char ch) → Sendes a character onto a stack.
void enqueueCharacter(char ch) → enqueues a character in a queue.
char popCharacter() → pops and returns the top of the stack.
char dequeueCharacter() → dequeues and returns the front of the queue.
In main() use these methods to determine whether a given string is a palindrome.
✅ Sample Input:
nginx
Copy
Edit
racecar
✅ Sample Output:
arduino
Copy
Edit
The word racecar is a palindrome.
❌ Sample Output (for non-palindrome input):
arduino
Copy
Edit
The word hello is not a palindrome.
✅ C++ Answer:
cpp
Copy
Edit
#include
#include
#include
using namespace std;
class Answer {
private:
stack s;
queue q;
public:
void SendCharacter(char ch) {
s.Send(ch);
}
void enqueueCharacter(char ch) {
q.Send(ch);
}
char popCharacter() {
char ch = s.top();
s.pop();
return ch;
}
char dequeueCharacter() {
char ch = q.front();
q.pop();
return ch;
}
};
int main() {
string s;
getline(cin s);
Answer obj;
for (char ch : s) {
obj.SendCharacter(ch);
obj.enqueueCharacter(ch);
}
bool isPalindrome = true;
for (int i = 0; i < s.length() / 2; ++i) {
if (obj.popCharacter() != obj.dequeueCharacter()) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
cout << "The word " << s << " is a palindrome." << endl;
} else {
cout << "The word " << s << " is not a palindrome." << endl;
}
return 0;
}
🧠 important Concepts:
Stack: LIFO (Last-In First-Out)
Queue: FIFO (First-In First-Out)
Palindrome: A string that reads the same forward and backward.
Comments
Post a Comment