帮我用c++语言实现该代码:必做:教材课后第二题:回文是指正读和反读都相同的字符序列,如“abba”和“abdba”,但是“good”不是回文。试写一个算法判定给定字符是否是回文。(提示:一半字符入栈)
时间: 2023-10-30 10:35:33 浏览: 77
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
int top = -1;
char stack[MAX_SIZE];
void push(char c) {
if (top == MAX_SIZE - 1) {
printf("Stack overflow\n");
return;
}
stack[++top] = c;
}
char pop() {
if (top == -1) {
printf("Stack underflow\n");
return '\0';
}
return stack[top--];
}
int main() {
char str[MAX_SIZE];
printf("Enter a string: ");
scanf("%s", str);
int len = strlen(str);
int mid = len / 2;
int i;
for (i = 0; i < mid; i++) {
push(str[i]);
}
if (len % 2 != 0) {
i++;
}
while (str[i] != '\0') {
char c = pop();
if (c != str[i]) {
printf("%s is not a palindrome\n", str);
return 0;
}
i++;
}
printf("%s is a palindrome\n", str);
return 0;
}
阅读全文