回文是指从前往后读和从后往前读是一样的字符串,例如"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
函数进行判断并输出结果。