C语言使用栈和队列来判断回文
算法思想
使用栈和队列来分别接受输入的字符串,利用栈先进后出,队列先进先出的特点进行前后比较来判断是否是回文
你可以使用双端队列更好的解决问题。
使用数组的话,代码又长又不高效
#include<stdio.h>
#include<stack>
#include<queue>
#include<iostream>
using namespace std;
#define MaxSize 50
bool isHWord(char* str) {
stack<char> p;
queue<char> q;
string Hword= str;
for (int i = 0; i < Hword.length(); i++) {
char s= Hword[i];
p.push(s);
q.push(s);
}
while (!p.empty() && !q.empty()) {
if (p.top() != q.front()) {
break;
}
p.pop();
q.pop();
}
return p.empty() && q.empty();
}
int main() {
while(1){
printf( "输入一个字符串:");
char str[MaxSize];
gets(str);
isHWord(str) ? printf("是回文!\n") :printf("不是回文\n");//调用函数进行判断
}
return 0;
}