使用堆栈和队列的回文程序
Palindrome program using stack and queue
我正在编写一个C++程序,通过使用堆栈和队列来确定用户输入的字符串是否为回文。
当我去编译程序时,程序成功编译了。然而,当我执行程序时,我键入一系列字符来测试它是否是回文,然后程序的光标闪烁,我必须取消程序,否则执行将在屏幕上暂停。我以前从未遇到过这个问题。
我使用cout语句来确定问题从哪里开始,并确定问题从最后一个if语句开始。
我从其他人那里找到了很多关于回文C++程序的例子,并试图比较我的例子,但几个小时后我就没有运气了。
你能解释一下我所描述的问题为什么会发生吗?我很感激你能提供的任何帮助!提前谢谢!
这是我的代码:
#include <iostream>
using namespace std;
#include "Stack.h"
#include "Queue.h"
int main (void)
{
Stack s;
Queue q;
string letter;
int length;
int notmatch;
notmatch=0;
cout<<"Please enter a series of characters."<<endl;
cin>>letter;
length = letter.size();
for (int i=1; i <= length; i++)
{
q.enqueue(i);
s.push(i);
}
while ((!q.empty()) && (!s.empty()))
{
if (s.top() != q.front() )
{
notmatch++;
q.dequeue();
s.pop();
}
}
if (notmatch == 0)
{
cout<<"The entered series of characters is a palindrome."<<endl;
}
else
{
cout<<"The entered series of characters is not a palindrome."<<endl;
}
}
因此,根据我对收到的评论的理解(谢谢!),我有:
#include <iostream>
using namespace std;
#include "Stack.h"
#include "Queue.h"
int main (void)
{
Stack s;
Queue q;
string letter;
int length;
cout<<"Please enter a series of characters."<<endl;
cin>>letter;
length = letter.size();
for (int i=0; i<length; i++)
{
q.enqueue(i);
s.push(i);
}
bool isPalindrome = true;
while (isPalindrome && (!q.empty()) && (!s.empty()))
{
if (s.top() != q.front() )
{
isPalindrome = false;
}
else
{
q.dequeue();
s.pop();
}
}
if(isPalindrome == false)
{
cout<<"Not a palindrome."<<endl;
}
else
{
cout<<"Is a palindrome."<<endl;
}
}
问题在这里
while ((!q.empty()) && (!s.empty()))
{
if (s.top() != q.front() )
{
notmatch++;
q.dequeue();
s.pop();
}
}
如果if
语句中的条件为true(这意味着它不是回文),你就不应该像@Jagannath所指出的那样继续循环,另一方面,如果条件为false(意味着它可能是回文)那么什么都不会发生,所以你的堆栈和队列不是空的,这会导致无限循环,这就是你需要终止程序的原因。
我认为这应该停止无休止的循环:
bool isPalindrome = true;
while (isPalindrome && (!q.empty()) && (!s.empty()))
{
if (s.top() != q.front() )
{
isPalindrome = false;
}
else
{
q.dequeue();
s.pop();
}
}
相关文章:
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- C++ 回文程序总是给出 0(假)作为输出问题;我的代码哪里有问题?
- 程序以查找给定字符串中回文的子字符串的数量
- 如何创建一个程序来标识最长的子字符串回文,而不考虑字母大小写
- 测试回文时程序不会继续运行 (C++)
- 回文程序和条件跳转或移动取决于未初始化的值
- C 中的回文数程序
- 使用 C++ 的回文程序的不需要的输出
- 内联程序集 - 检查单词是否为回文
- 使用数组的 C++ 回文程序
- 回文程序中非常奇怪的问题
- C++回文程序
- 堆栈和队列回文程序
- 使用堆栈和队列的回文程序
- 在制作回文程序 C++ 时遇到困难
- 字符串回文程序不会忽略案例
- 我的回文程序给出了一个例外
- 不能在回文程序中输入多个字符串
- 回文程序和 C 样式字符串中不需要的字符
- 回文c++程序