数据结构——回文串判断(C语言)
时间: 2023-08-31 10:09:14 浏览: 92
Sure, I'd be happy to help you with that question! For checking if a string is a palindrome, you can use a stack data structure to store the characters in the first half of the string, and then compare them to the characters in the second half of the string. Here's an example implementation in C:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 100
typedef struct {
char data[MAX_LENGTH];
int top;
} Stack;
void push(Stack *s, char c) {
if (s->top == MAX_LENGTH - 1) {
printf("Error: stack overflow!\n");
exit(1);
}
s->data[++(s->top)] = c;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Error: stack underflow!\n");
exit(1);
}
return s->data[(s->top)--];
}
int is_palindrome(char *s) {
int len = strlen(s);
Stack stack;
stack.top = -1;
int i;
for (i = 0; i < len/2; i++) {
push(&stack, s[i]);
}
if (len % 2 == 1) {
i++;
}
for (; i < len; i++) {
if (pop(&stack) != s[i]) {
return 0;
}
}
return 1;
}
int main() {
char str[MAX_LENGTH];
printf("Enter a string: ");
fgets(str, MAX_LENGTH, stdin);
str[strcspn(str, "\n")] = '\0'; // remove newline character from input
if (is_palindrome(str)) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
```
I hope that helps! Let me know if you have any other questions.