#include <stdlib.h>
#include "stdio.h"
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define true 1
#define false -1
typedef char ElemType;
typedef int bool ;
typedef struct Node
{
char data;
struct Node *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
typedef struct Stack
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
// 初始化队列
bool InitQueue(LinkQueue *Q)
{
Q->front = Q->rear = (QueuePtr)malloc(sizeof (QNode));
if (!Q->front)
{
exit(0);
}
Q->front->next = NULL;
return true;
}
// 插入元素到队列
bool EnQueue(LinkQueue *Q, ElemType e)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if (!p)
{
exit(0);
}
p->data = e;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
return true;
}
// 从队列中删除元素
bool DeQueue(LinkQueue *Q, ElemType *e)
{
QueuePtr p;
if (Q->front == Q->rear) //空队列
{
return false;
}
p = Q->front->next;//p指向头结点的下个位置
*e = p->data;
Q->front->next = p->next;
if (Q->rear == p)
{
Q->rear = Q->front;
}
free(p);
return true;
}
// 初始化栈
bool InitStack(SqStack *S)
{
S->base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if (S->base == NULL)
{
return false;
}
S->top = S->base;
S->stacksize = STACK_INIT_SIZE;
return true;
}
// 元素入栈
bool Push(SqStack *S, ElemType e)
{
if (S->top - S->base >= S->stacksize)
{
S->base = (ElemType *)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(ElemType));
if (!S->base)
{
return false;
}
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top++) = e;
return true;
}
// 元素出栈
bool Pop(SqStack *S, ElemType *e)
{
if (S->top == S->base)
return false;
*e = (*--S->top);
return true;
}
bool IsPalindrome(char c[]){
ElemType a,b;
int i = 0;
// int flag1 = 0;
// int flag2 = 0;
SqStack S;
LinkQueue L;
InitStack (&S);
InitQueue (&L);
while (c[i] != '@')
{
Push(&S,c[i]);
EnQueue(&L,c[i]);
// flag1++;
i++;
}
for (i; i > 0; i--) {
Pop(&S,&b);
DeQueue(&L,&a);
if (a != b)
return false;
}
return true;
}
int main ()
{
int str;
char c[10];
printf("请输入要判断的字符,以@结束(最多10个字符):");
scanf("%s",c);
str = IsPalindrome(c);
if (str == true)
printf("该序列是回文数!\n");
else
printf("该序列不是回文数!\n");
return 0;
}
栈和队列判断回文数
猜你喜欢
转载自blog.csdn.net/qq_44880095/article/details/105698485
今日推荐
周排行