0

我使用堆栈和队列来检查给定的单词是否是回文。我可以将一个新字符推入堆栈,但我不能将多个字符推入队列。我看不到代码中的错误在哪里。任何帮助将不胜感激。下面是使用 Dev-C++ 的 C++ 代码。谢谢你的时间!

#include <iostream>
#include <stack>
#include <queue>
#include <string>

using namespace std;

void push_char()
{

  string givenword; int sizeword, countchar;
  string letter;
  stack<string> stackword; string stawo1;
  queue<string>  queueword; string quewo1;

  cout<<"enter the word to test "<<endl;
  getline(cin,givenword);
  string str (givenword);
  sizeword=str.size();
  cout<<" the word given   "<<givenword<<"   size of word= "<<sizeword  <<endl;
  countchar=0;
  bool pali=true;

  while ((countchar<sizeword))
  {          
    stackword.push(str.substr(countchar,1));
    queueword.push(str.substr(countchar,1));
    cout<<" stack letter= "<<stackword.top()<<" queue letter= "<<queueword.front()<<endl;
    countchar++;

    if(stackword.top()==queueword.front())
      cout<<"same letter found !"<<endl;
    else
      pali=false;

    if (pali==false)
      cout<<"not a palindrome"<<endl;
    else
      cout<<"palindrome!"<<endl;
  }
}

int main()
{
  push_char();
}
4

3 回答 3

0

有更好的方法可以找到回文......但这不是你问的问题。

在这一行中: if(stackword.top()==queueword.front())

是你的错误所在。当你推入队列时,你会推到队列的末尾。正面不会改变。所以对你来说,它似乎只有一件事。

当您压入堆栈时,它会压入现有堆栈的顶部。

于 2011-11-02T04:11:28.377 回答
0

仅供参考,您可以使用 str[countchar] 而不是 str.substr(countchar,

几点:

1)你的代码很好,你的算法不是。拿一张纸,逐步完成你正在做的事情。

2)我明白你在做什么......像这样的未经测试的代码,对吧?

for(int i=0; i<sizeword; ++i) {
  stackword.push(str[i]);
  queueword.push(str[i]);
}

pali = true;
for(int i=0; i<sizeword; ++i) {
  if(stackword.top() != queueword.front()) {
    pali = false;
    break;
  }
  stackword.pop();
  queueword.pop();
}
于 2011-11-02T04:26:51.653 回答
0

你有两个选择。第一个是 aleph_null 建议的 - 双通道,您在第一通道中将字符添加到容器中,并在第二通道中比较它们。第二种选择是按照您的方式比较它们,但要查看单词的两端。您实际上不需要任何容器,但只需对您的 while 循环进行最小的更改,代码应如下所示:

while ((countchar<sizeword))
{          
  stackword.push(str.substr(countchar,1));
  queueword.push(str.substr(sizeword - 1 - countchar,1)); // adding from the back
  cout<<" stack letter= "<<stackword.top();
  cout<<" queue letter= "<<queueword.back()<<endl; // .back() not .front()
  countchar++;

  if(stackword.top()==queueword.back()) // again, looking at the last added char
    cout<<"same letter found !"<<endl;
  else
    pali=false;

  // as Joe McGrath pointed out this should probably be outside the loop...
  if (pali==false)
    cout<<"not a palindrome"<<endl;
  else
    cout<<"palindrome!"<<endl;
}

希望有帮助。

罗马

于 2011-11-03T16:06:24.810 回答