输入一串字符以回车结束利用栈和队列来判断它是否是回文用C语言编写代码
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h>
#define MAX_LEN 100 // 字符串最大长度
typedef struct Stack { char data[MAX_LEN]; int top; } Stack;
typedef struct Queue { char data[MAX_LEN]; int front; int rear; } Queue;
void initStack(Stack *s) { s->top = -1; }
void initQueue(Queue *q) { q->front = q->rear = 0; }
bool isEmptyStack(Stack *s) { return s->top == -1; }
bool isEmptyQueue(Queue *q) { return q->front == q->rear; }
bool isFullQueue(Queue *q) { return q->rear == MAX_LEN; }
void push(Stack *s, char c) { if (s->top == MAX_LEN - 1) { printf("Stack is full.\n"); return; } s->data[++s->top] = c; }
char pop(Stack *s) { if (isEmptyStack(s)) { printf("Stack is empty.\n"); return '\0'; } return s->data[s->top--]; }
void enqueue(Queue *q, char c) { if (isFullQueue(q)) { printf("Queue is full.\n"); return; } q->data[q->rear++] = c; }
char dequeue(Queue *q) { if (isEmptyQueue(q)) { printf("Queue is empty.\n"); return '\0'; } return q->data[q->front++]; }
bool isPalindrome(char *s) { int len = strlen(s); Stack s1; Queue q1; initStack(&s1); initQueue(&q1); for (int i = 0; i < len; i++) { char c = s[i]; push(&s1, c); enqueue(&q1, c); } while (!isEmptyStack(&s1) && !isEmptyQueue(&q1)) { char c1 = pop(&s1); char c2 = dequeue(&q1); if (c1 != c2) { return false; } } return true; }
int main() { char s[MAX_LEN]; printf("Please input a string:\n"); fgets(s, MAX_LEN, stdin); if (isPalindrome(s)) { printf("Yes, it is a palindrome.\n"); } else { printf("No, it is not a palindrome.\n"); } return 0;
原文地址: http://www.cveoy.top/t/topic/dw8A 著作权归作者所有。请勿转载和采集!