使用堆栈和队列的回文程序

Palindrome program using stack and queue

本文关键字:回文 程序 队列 堆栈      更新时间:2023-10-16

我正在编写一个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();
    }
}