在C语言中使用栈来识别回文结构

   2024-10-20 7700
核心提示:下面是一个使用栈来识别回文结构的C语言示例代码:#include stdio.h#include string.h#include stdlib.h#include stdbool.h#defi

下面是一个使用栈来识别回文结构的C语言示例代码:

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <stdbool.h>#define MAX_SIZE 100typedef struct {    char data[MAX_SIZE];    int top;} Stack;void init(Stack *stack) {    stack->top = -1;}void push(Stack *stack, char value) {    if (stack->top < MAX_SIZE - 1) {        stack->data[++stack->top] = value;    }}char pop(Stack *stack) {    if (stack->top >= 0) {        return stack->data[stack->top--];    }    return '\0';}bool isPalindrome(char *str) {    Stack stack;    init(&stack);    int length = strlen(str) / 2;    for (int i = 0; i < length; i++) {        push(&stack, str[i]);    }    int start = length;    if (strlen(str) % 2 == 1) {        start++;    }    for (int i = start; i < strlen(str); i++) {        if (str[i] != pop(&stack)) {            return false;        }    }    return true;}int main() {    char str[MAX_SIZE];    printf("Enter a string: ");    scanf("%s", str);    if (isPalindrome(str)) {        printf("The string is a palindrome.\n");    } else {        printf("The string is not a palindrome.\n");    }    return 0;}

在这个示例中,我们定义了一个栈结构体和相关的操作函数。然后我们定义了一个isPalindrome函数来判断输入的字符串是否是回文结构。最后在main函数中输入一个字符串,并调用isPalindrome函数来判断该字符串是否是回文结构。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号