用c++编写一个回文是指正读和反读均相同的字符序列,如”abba”和”abdba”均是回文,但”good”不是回文,试写一算法利用栈判定给定的字符序列是否为回文。(提示:将一半字符入栈
时间: 2023-10-30 21:52:34 浏览: 69
由c++实现的用栈实现回文数据的判断
5星 · 资源好评率100%
#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 is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAXSIZE - 1;
}
void push(Stack *s, char c) {
if (is_full(s)) {
printf("Stack overflow\n");
return;
}
s->top++;
s->data[s->top] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack underflow\n");
return '\0';
}
char c = s->data[s->top];
s->top--;
return c;
}
int main() {
char str[MAXSIZE];
printf("Enter a string: ");
scanf("%s", str);
int len = strlen(str);
Stack s;
init(&s);
int i;
for (i = 0; i < len / 2; i++) {
push(&s, str[i]);
}
if (len % 2 != 0) {
i++;
}
for (; i < len; i++) {
if (pop(&s) != str[i]) {
printf("%s is not a palindrome\n", str);
return 0;
}
}
printf("%s is a palindrome\n", str);
return 0;
}
阅读全文