#include #include #include #define MAX_SIZE 100 typedef struct { char data[MAX_SIZE]; int front; int rear;
} Queue; Queue* createQueu"> #include #include #include #define MAX_SIZE 100 typedef struct { char data[MAX_SIZE]; int front; int rear;
} Queue; Queue* createQueu">
117.info
人生若只如初见

C语言中利用队列数据结构识别回文

回文是指从前往后读和从后往前读是一样的字符串,例如"level"和"radar"。下面是一个利用队列数据结构来识别回文的C语言代码示例:

#include 
#include 
#include 

#define MAX_SIZE 100

typedef struct {
    char data[MAX_SIZE];
    int front;
    int rear;
} Queue;

Queue* createQueue() {
    Queue* q = (Queue*)malloc(sizeof(Queue));
    q->front = -1;
    q->rear = -1;
    return q;
}

void enqueue(Queue* q, char value) {
    if (q->rear == MAX_SIZE - 1) {
        printf("Queue is full\n");
    } else {
        q->rear++;
        q->data[q->rear] = value;
    }
}

char dequeue(Queue* q) {
    if (q->front == q->rear) {
        printf("Queue is empty\n");
        return '\0';
    } else {
        q->front++;
        return q->data[q->front];
    }
}

int isPalindrome(char* str) {
    Queue* q = createQueue();
    
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
        enqueue(q, str[i]);
    }
    
    for (int i = 0; i < len; i++) {
        char c = dequeue(q);
        if (c != str[i]) {
            return 0;
        }
    }
    
    return 1;
}

int main() {
    char str[MAX_SIZE];
    printf("Enter a string: ");
    scanf("%s", str);
    
    if (isPalindrome(str)) {
        printf("%s is a palindrome\n", str);
    } else {
        printf("%s is not a palindrome\n", str);
    }
    
    return 0;
}

在这个示例中,我们首先定义了一个队列结构Queue,并实现了创建队列、入队和出队等基本操作。然后我们定义了isPalindrome函数来判断输入的字符串是否为回文。在该函数中,我们首先将字符串中的字符逐个入队,然后再逐个出队并与原字符串进行比较,如果有任何一个字符不相同,则返回0,表示不是回文;如果所有字符都相同,则返回1,表示是回文。最后在main函数中,我们接收用户输入的字符串,并调用isPalindrome函数进行判断并输出结果。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fe552AzsIBgRWBlw.html

推荐文章

  • c语言goto用法是什么

    在C语言中,goto语句用于从一个位置跳转到另一个位置。它可以用于跳出循环、条件语句或者函数。goto语句的语法如下:
    goto label;
    ...
    label: //...

  • goto在c语言中的运用方法是什么

    goto 语句在 C 语言中允许程序从一个位置跳转到另一个位置。然而,在实际编程中,过度使用 goto 语句通常被认为是一种不好的编程实践,因为它可能导致代码结构混...

  • c语言堆和栈的区别是什么

    C语言中的堆和栈是两种不同的内存分配方式。 栈(Stack):栈是由编译器自动分配和释放的内存区域,用于存储局部变量和函数调用的上下文信息。栈的特点是先进后出...

  • C语言结构体数组怎么定义和使用

    在C语言中,可以通过定义结构体数组来存储多个具有相同数据类型的结构体对象。下面是定义和使用结构体数组的示例代码:
    #include // 定义一个结构体类型

  • 结合C语言和算法学习:回文检测的多种方法

    方法一:利用数组和循环比较 #include #include int isPalindrome(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != st...

  • 分析C语言中处理回文问题时的算法复杂度

    在 C 语言中处理回文问题时,一种常用的算法是首尾指针法。该算法通过两个指针分别从字符串的首尾向中间移动,比较对应位置的字符是否相等,直到两个指针相遇或交...

  • C语言中处理回文的常见错误及其修正方法

    错误:忽略大小写 在处理回文时,有时会忽略字符串中的大小写,导致判断错误。
    修正方法:在比较字符时,统一转换成小写或大写,然后再进行比较。 错误:忽...

  • 利用C语言探究回文结构在密码学中的应用

    在密码学中,回文结构可以用来创建一种对称加密算法。对称加密算法是一种加密和解密使用相同密钥的加密方法,也就是说发送方和接收方需要共享同一个密钥。
    ...