我正在尝试创建一个palindrome函数。我必须拿一根绳子并将其放在队列中,堆栈。然后将它们比较,看看它们是否是回文。在我的功能中,我已经取出了空间,将所有字母转换为较低的情况,现在我试图比较堆栈和队列以查看给定的单词是否是alsindrome。但是我不能这样做,因为错误消息"类型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;
}
pop()
返回void
,因此您的错误。首先,您应该从容器中获取值,然后从容器中获得pop
。请注意,您应该将top
用于std::stack
和front
或back
用于std::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;