回文是指正读和反读均相同的字符序列,如”abba”和”abdba”均是回文,但”good”不是回文,试用c语言写一算法利用栈判定给定的字符序列是否为回文。(提示:将一半字符入栈)
时间: 2023-10-30 07:18:39 浏览: 120
```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 initStack(Stack *s) {
s->top = -1;
}
bool isStackEmpty(Stack *s) {
return s->top == -1;
}
bool isStackFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, char c) {
if (isStackFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->top++;
s->data[s->top] = c;
}
char pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
char c = s->data[s->top];
s->top--;
return c;
}
bool isPalindrome(char *str) {
int len = strlen(str);
Stack s;
initStack(&s);
int i;
for (i = 0; i < len / 2; i++) {
push(&s, str[i]);
}
if (len % 2 == 1) {
i++;
}
while (str[i] != '\0') {
if (pop(&s) != str[i]) {
return false;
}
i++;
}
return true;
}
int main() {
char str[MAX_SIZE];
printf("Input a string: ");
scanf("%s", str);
if (isPalindrome(str)) {
printf("%s is palindrome.\n", str);
} else {
printf("%s is not palindrome.\n", str);
}
return 0;
}
```
阅读全文