c++ - 使用栈和队列的回文程序

标签 c++

我正在编写一个 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 语句中的条件为真(这意味着不是回文)你不应该像@Jagannath 指出的那样继续循环,另一方面如果条件为假(这意味着它可能是回文)然后什么也没有发生,所以你的堆栈和队列不为空,这会导致无限循环,这就是你需要终止程序的原因。

我相信这应该会停止无限循环:

bool isPalindrome = true;
while (isPalindrome && (!q.empty()) && (!s.empty()))
{
    if (s.top() != q.front() )
    {
        isPalindrome = false;
    }
    else
    {
        q.dequeue();
        s.pop();
    }
}

关于c++ - 使用栈和队列的回文程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423439/

相关文章:

c++ - 如何在MFC中查找系统是否有我需要的字体?

c++ - 播放器结构生成 C2440 错误

c++ - 进程间通信 - 二进制数据/序列化对象

c++ - 使用 enable_if 匹配数字作为函数参数

c++ - 叉积的输出

android - 如何加快 android ndk 构建

c++ - 拆分逗号分隔的字符串

c++ - basic_string 等价物的单元测试

c++ - 如何让 BOOST_TEST_MESSAGE 显示在屏幕上?

c++ - 无限循环问题