c语言利用栈和队列完成回文的判断代码
时间: 2023-12-24 13:03:01 浏览: 143
huiw.dsp.rar_回文栈和队列_用栈和队列编写判断回文的c语言程序
好的,以下是 C 语言利用栈和队列实现回文判断的代码示例:
```c
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int top;
}SqStack;
typedef struct QNode
{
ElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front, rear;
}LinkQueue;
void InitStack(SqStack *S)
{
S->top = -1;
}
int StackEmpty(SqStack S)
{
if(S.top == -1) return 1;
else return 0;
}
int StackFull(SqStack S)
{
if(S.top == MAXSIZE - 1) return 1;
else return 0;
}
void Push(SqStack *S, ElemType x)
{
if(StackFull(*S))
{
printf("Stack is full!\n");
exit(1);
}
else
{
S->data[++S->top] = x;
}
}
ElemType Pop(SqStack *S)
{
if(StackEmpty(*S))
{
printf("Stack is empty!\n");
exit(1);
}
else
{
return S->data[S->top--];
}
}
void InitQueue(LinkQueue *Q)
{
Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q->front)
{
printf("Memory allocation failed!\n");
exit(1);
}
Q->front->next = NULL;
}
void EnQueue(LinkQueue *Q, ElemType x)
{
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if(!p)
{
printf("Memory allocation failed!\n");
exit(1);
}
p->data = x;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
}
ElemType DeQueue(LinkQueue *Q)
{
QueuePtr p;
ElemType x;
if(Q->front == Q->rear)
{
printf("Queue is empty!\n");
exit(1);
}
p = Q->front->next;
Q->front->next = p->next;
x = p->data;
if(Q->rear == p)
Q->rear = Q->front;
free(p);
return x;
}
int main()
{
SqStack s;
LinkQueue q;
int n, i, flag = 1;
char c[MAXSIZE];
printf("Input a string:");
gets(c);
n = strlen(c);
InitStack(&s);
InitQueue(&q);
for(i = 0; i < n; i++)
{
if(c[i] >= 'A' && c[i] <= 'Z')
c[i] = c[i] + 32;
if(c[i] >= 'a' && c[i] <= 'z')
{
Push(&s, c[i]);
EnQueue(&q, c[i]);
}
}
while(!StackEmpty(s) && flag)
{
if(Pop(&s) != DeQueue(&q))
flag = 0;
}
if(flag == 1)
printf("The string is a palindrome!\n");
else
printf("The string is not a palindrome!\n");
return 0;
}
```
请问您还有什么需要我帮忙的吗?
阅读全文