回文是指正读反读均相同的字符序列,如“abb a”和“abdba”均是回文,但“good”不是回文。试写一个链栈c语言算法判定给定的字符向量是否为回文。(提示:将一半字符入栈)
时间: 2023-10-30 09:20:51 浏览: 85
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct Node{
char data;
struct Node *next;
}Node, *Stack;
Stack createStack(){
Stack s = (Stack)malloc(sizeof(Node));
s->next = NULL;
return s;
}
int isEmpty(Stack s){
return s->next == NULL;
}
void push(Stack s, char data){
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->data = data;
new_node->next = s->next;
s->next = new_node;
}
char pop(Stack s){
if(isEmpty(s)){
printf("Stack is empty!\n");
exit(1);
}
Node *p = s->next;
s->next = p->next;
char data = p->data;
free(p);
return data;
}
int palindrome(char *str){
Stack s = createStack();
int len = strlen(str);
int mid = len / 2;
int i;
for(i = 0; i < mid; i++){
push(s, str[i]);
}
if(len % 2 == 1) i++;
while(str[i] != '\0'){
if(str[i] != pop(s)){
return 0;
}
i++;
}
return 1;
}
int main(){
char str[MAX_SIZE];
printf("Enter a string: ");
fgets(str, MAX_SIZE, stdin);
str[strlen(str)-1] = '\0'; //去掉fgets读入的换行符
if(palindrome(str)){
printf("%s is a palindrome.\n", str);
}else{
printf("%s is not a palindrome.\n", str);
}
return 0;
}
```
阅读全文