步骤:1.通过InitStack()函数来初始化栈
2.通过Push()函数来压栈
3.通过Pop()函数来弹栈
4.通过StackEmpty()函数来进行栈的判空
5.通过Panduan()函数来进行回文判定
- 算法分析
回文的判定关键在于字符串是否是关于中心元素对称的,即将字符串逆序在与原字符串进行比较。由于栈具有先进后出的特点,所以栈是该问题的最佳解决方法,将字符串入栈,然后再进行弹出操作,与原字符串进行比较,相同即为回文。
考虑到待测字符串会有长短的不同,短字符串用上述方法即可,但长字符串会造成时间的浪费,这时就应考虑回文的另一特点:是关于中心元素对称的。所以为了节省时间可以先将一半的字符串入栈然后再出栈与剩下的字符进行比对,当比对结果全部正确时,即为回文,反之则不是。
程序流程图如下:
代码如下:
/*name:雷桂艺
time:2021年12月8日17:32
version:1.0
description:步骤:
1.通过InitStack()函数来初始化栈
2.通过Push()函数来压栈
3.通过Pop()函数来弹栈
4.通过Empty()函数来进行栈的判空
5.通过Panduan()函数来进行回文判定
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//定义栈
typedef char ElemType;
typedef struct
{
int stack_size;
ElemType *top;
ElemType *base;
}Stack;
enum Status{ ERROR, OK };
Status InitStack(Stack &S, ElemType *t) //初始化栈
{
int len = strlen(t);
S.base = (ElemType *)malloc(len * sizeof(ElemType));
if (S.base == NULL)
return ERROR;
S.top = S.base;
S.stack_size = len;
}
//入栈
Status Push(Stack &S, ElemType e)
{
if (S.top - S.base == S.stack_size)
return ERROR;
*S.top++ = e;
return OK;
}
//出栈
Status Pop(Stack &S, ElemType &e)
{
if (S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
//判空
int StackEmpty(Stack S)
{
return (S.top == S.base);
}
Status Panduan(ElemType *t) //判断t[]是否为回文
{
Stack S;
ElemType e;
int i, len;
InitStack(S, t);
len = strlen(t); //求数组长度
for (i = 0; i<len / 2; i++)//将一半字符入栈
Push(S, t[i]);
if (strlen(t) % 2 == 1)
i++;
while (!StackEmpty(S))// 每弹出一个字符与相应字符比较
{
Pop(S, e);
if (e != t[i])
return ERROR;// 不等则返回0
else i++;
}
return OK; // 比较完毕均相等
}
int main()
{
int len = 0;
ElemType *a = NULL;
printf("你要输入几个字符:");
scanf("%d", &len);
getchar(); //吃掉回车
a = (ElemType *)malloc(len * sizeof(ElemType));
printf("\n请输入待检测的字符串:");
gets_s(a,len+1);
if (Panduan(a))
printf("\n是回文字符串");
else
printf("\n不是回文字符串");
return 0;
}