用C语言写一个代码,题目描述如下:文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。试写一个算法判定给定的字符向量是否为回文。(提示:将一半字符入栈)
时间: 2023-10-30 15:07:23 浏览: 72
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100 // 字符向量最大长度
typedef struct {
char data[MAX_SIZE];
int top; // 栈顶位置
} Stack;
void init(Stack *s) {
s->top = -1;
}
bool is_empty(Stack *s) {
return s->top == -1;
}
bool is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, char c) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
bool is_palindrome(char *str) {
Stack s;
init(&s);
int len = strlen(str);
int i;
for (i = 0; i < len / 2; i++) {
push(&s, str[i]);
}
if (len % 2 != 0) {
i++;
}
while (str[i] != '\0') {
if (pop(&s) != str[i]) {
return false;
}
i++;
}
return true;
}
int main() {
char str[MAX_SIZE];
printf("Enter a string: ");
scanf("%s", str);
if (is_palindrome(str)) {
printf("%s is palindrome.\n", str);
} else {
printf("%s is not palindrome.\n", str);
}
return 0;
}
```
阅读全文