回文是指正读和反读均相同的字符序列,如”abba”和”abdba”均是回文,但”good”不是回文,试写一算法利用栈判定给定的字符序列是否为回文。(提示:将一半字符入栈)使用c语言
时间: 2023-10-30 09:28:22 浏览: 84
判断字符序列是否是回文
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} Stack;
void InitStack(Stack *s) {
s->top = -1;
}
int StackEmpty(Stack *s) {
if (s->top == -1)
return 1;
else
return 0;
}
int StackFull(Stack *s) {
if (s->top == MAXSIZE - 1)
return 1;
else
return 0;
}
void Push(Stack *s, char x) {
if (StackFull(s)) {
printf("Stack is full.\n");
exit(0);
}
s->data[++s->top] = x;
}
char Pop(Stack *s) {
if (StackEmpty(s)) {
printf("Stack is empty.\n");
exit(0);
}
return s->data[s->top--];
}
int main() {
Stack s;
InitStack(&s);
char str[MAXSIZE];
printf("Enter a string: ");
scanf("%s", str);
int len = strlen(str);
int i;
for (i = 0; i < len/2; i++)
Push(&s, str[i]);
if (len % 2 != 0)
i++;
while (i < len) {
if (Pop(&s) != str[i]) {
printf("%s is not a palindrome.\n", str);
return 0;
}
i++;
}
printf("%s is a palindrome.\n", str);
return 0;
}
阅读全文