Palindrome字符回文 (C语言)

#include <stdio.h>
#include <stdlib.h>
#define STACKSIZE 10	 //栈存储空间的初始分配量
#define STACKINCREMENT 5 //栈分配空间的分配增量
#define MAXQSIZE 100	 //队列存储空间的初始分配量

typedef struct
{
	char *base;
	char *top;
	int stacksize; //栈可用的最大容量
} SqStack;

typedef struct
{
	char *base;
	int front; //头指针,若队列不为空,指向队列头元素
	int rear;  //尾指针,若队列不为空,指向队尾元素的下一个位置
} SqQueue;

int main()
{
	SqStack S;
	SqQueue Q;
	int ending;
	char e, h, c, e1, e2;
	int InitStack(SqStack * S);		  //栈的初始化
	int Push(SqStack * S, char e);	  //入栈
	char Pop(SqStack * S);			  //出栈
									  //	void PrintStack(SqStack * S);	   //遍历栈
	int InitQueue(SqQueue * Q);		  //队列初始化
	int EnQueue(SqQueue * Q, char h); //入队
	char DeQueue(SqQueue * Q);		  //出队
									  //	int PrintQueue(SqQueue * Q);	   //遍历队列

	InitStack(&S);
	InitQueue(&Q);
	printf("请输入字符序列,以@结束:");
	while ((c = getchar()) != '@')
	{
		Push(&S, c);
		EnQueue(&Q, c);
	}

	/*printf("\n出栈后SqStack:");
	PrintStack(&S);
	printf("\n入队后SqQueue:");
	PrintQueue(&Q);*/

	while (S.top != S.base)
	{
		e1 = Pop(&S);
		e2 = DeQueue(&Q);
		if (e1 == e2)
			ending = 1;
		else
		{
			ending = 0;
			break;
		}
	}
	if (ending)
	{
		printf("该字符序列是回文序列。\n");
		return 0;
	}
	else
	{
		printf("该字符序列不是回文序列。\n");
		return 0;
	}
}

//栈的初始化
int InitStack(SqStack *S)
{
	S->base = (char *)malloc(STACKSIZE * sizeof(char));
	if (!S->base)
	{
		printf("内存地址分配失败!error!");
		exit(-1);
	}
	S->top = S->base;
	S->stacksize = STACKSIZE;
	return 0;
}

//入栈
int Push(SqStack *S, char e)
{
	if (S->top - S->base == S->stacksize)
		exit(-1); //栈满
	*S->top++ = e;
	return 0;
}

//出栈
char Pop(SqStack *S)
{
	char e;
	if (S->top == S->base)
		exit(-1); //栈空
	e = *--S->top;
	return e;
}

/*遍历栈
void PrintStack(SqStack *S)
{
	char *p = S->base;
	while (p != S->top)
	{
		printf("%c", *p++);
	}
	printf("\n");
}*/

//队列初始化
int InitQueue(SqQueue *Q)
{
	Q->base = (char *)malloc(MAXQSIZE * sizeof(char));
	if (Q->base)
	{
		Q->front = Q->rear = 0;
		return 0;
	}
	else
	{
		printf("ERROR!内存分配失败!");
		exit(-1);
	}
}

//入队
int EnQueue(SqQueue *Q, char h)
{
	if ((Q->rear + 1) % MAXQSIZE == Q->front)
	{
		printf("队列已满!\n");
		exit(-1);
	} //队满
	Q->base[Q->rear] = h;
	Q->rear = (Q->rear + 1) % MAXQSIZE;
	return 0;
}

//出队
char DeQueue(SqQueue *Q)
{
	char h;
	if (Q->front == Q->rear)
		exit(-1); //队列空
	h = Q->base[Q->front];
	Q->front = (Q->front + 1) % MAXQSIZE;
	return h;
}

/*遍历队列
int PrintQueue(SqQueue *Q)
{
	int i;
	if (Q->front == Q->rear)
		printf("空队列!\n");
	else
	{
		for (i = Q->front; Q->rear != i % MAXQSIZE; i = (i + 1) % MAXQSIZE)
			printf("%c", Q->base[i]);
	}
	printf("\n");
	return 0;
}*/

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值