回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。试写一个算法判定给定的字符向量是否为回文。(提示:将一半字符入栈) 用c语言实现
时间: 2023-10-30 11:05:45 浏览: 122
判断字符序列是否是回文
```c
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
typedef struct Stack {
char data[MAX_LENGTH];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
void push(Stack *s, char x) {
if (s->top == MAX_LENGTH - 1) {
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = x;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty.\n");
return '\0';
}
char x = s->data[s->top];
s->top--;
return x;
}
int is_palindrome(char *str) {
int len = strlen(str);
Stack s;
init(&s);
for (int i = 0; i < len / 2; i++) {
push(&s, str[i]);
}
for (int i = (len + 1) / 2; i < len; i++) {
if (str[i] != pop(&s)) {
return 0;
}
}
return 1;
}
int main() {
char str[MAX_LENGTH];
printf("Enter a string: ");
fgets(str, MAX_LENGTH, stdin);
if (is_palindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
```
阅读全文