回文函数(字符串,堆栈,队列)

时间:2012-10-22 00:03:50

标签: c++ string function stack queue

我正在尝试创建一个Palindrome函数。我必须把一个字符串放在一个队列堆栈中。然后比较它们,看它们是否是回文。在我的函数中,我取出了空格,将所有字母转换为小写,现在我试图比较STACK和QUEUE,看看给出的单词是否是回文。但由于错误消息“无法将类型为void的值分配给字符类型的实体”,我无法这样做。如果可能的话,请告诉我我做错了什么?

enter bool isPalindrome(string s){
//lowers all letters to lower case so it will not be case sensetive
for (int i = 0; i < s.length(); i ++)
    s[i] = tolower(s[i]);

 //removes white space from the word that is being checked
char c;
int i = 0;
while (s[i])
{
    c=s[i];
    if (isspace(c)) c='\n';
    putchar (c);
    i++;
}

queue<string> q1;
stack<string> s1;
for (int k = 0; k < s.size(); k++) 
    if (isalpha(s[k]))
        q1.push(s);

for (int u = 0; u < s.size(); u++)
    if (isalpha(s[u]))
        s1.push(s);
char e;
char d;
while (q1.size() > 0 )
     e = q1.pop();
     d = s1.pop();
    if (e != d)
        return false;
    else
    return true;

}

1 个答案:

答案 0 :(得分:2)

pop()返回void,因此您的错误。您应首先从容器中获取值,然后从容器中pop获取值。请注意,您应top使用std::stackfront使用backstd::queue

e = q1.front();
q1.pop();
d = s1.top();
s1.pop();

编辑:我忽略的另一个问题是你将整个字符串存储在队列(和堆栈)中并尝试将它们弹出到char中。所以你可能想做的就是:

std::queue<char>
std::stack<char>
for (int k = 0; k < s.size(); k++) 
    if (isalpha(s[k]))
        q1.push(s[k]);

for (int u = 0; u < s.size(); u++)
    if (isalpha(s[u]))
        s1.push(s[u]);

和堆栈相同。

EDIT2 :另一个遗漏位在最后while。循环周围应该有括号,return true语句应该在循环之后:

while (q1.size() > 0 ) {
    e = q1.front();
    q1.pop();
    d = s1.top();
    s1.pop();
    if (e != d)
        return false;
}
return true;
相关问题