用C语言设计一个程序用栈判断一个字符串是否为回文
时间: 2024-05-22 08:16:02 浏览: 61
C语言 判断字符串是否是回文
5星 · 资源好评率100%
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
char stack[MAX_SIZE];
int top = -1;
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 isPalindrome(char str[]) {
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
push(str[i]);
}
for (int i = len % 2 == 0 ? len / 2 : len / 2 + 1; i < len; i++) {
if (pop() != str[i]) {
return 0;
}
}
return 1;
}
int main() {
char str[MAX_SIZE];
printf("Enter a string: ");
scanf("%s", str);
if (isPalindrome(str)) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}
return 0;
}
阅读全文