c语言请设计一个算法,使用栈,判断一个字符串是否为回文。回文:是指正读反读均相同的字符序列,如abba和abdba都是回文,而hello就不是回文。(提示:使用数组存储一个字符串,然后将一半字符入栈。
时间: 2024-05-29 12:12:19 浏览: 38
#include <stdio.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int isEmpty(Stack s) {
return s.top == -1;
}
int isFull(Stack s) {
return s.top == MAXSIZE - 1;
}
void push(Stack *s, char x) {
if (isFull(*s)) {
printf("Stack overflow\n");
return;
}
s->data[++s->top] = x;
}
char pop(Stack *s) {
if (isEmpty(*s)) {
printf("Stack underflow\n");
return '\0';
}
return s->data[s->top--];
}
int main() {
char str[MAXSIZE];
Stack s;
int len, i;
printf("Enter a string: ");
scanf("%s", str);
len = strlen(str);
init(&s);
for (i = 0; i < len / 2; i++) {
push(&s, str[i]);
}
if (len % 2 != 0) {
i++;
}
while (i < len && str[i] == pop(&s)) {
i++;
}
if (i == len) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
阅读全文