产出:
CSDN 技术博客 1 篇
哔哩哔哩专栏1篇
问题
回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。试写一个算法判定给定的字符序列是否为回文。是回文。试写一个算法判定给定的字符序列是否为回文。
思路
总思路:将所有元素进栈,然后依次出栈与数组元素比较
具体步骤
1、键盘输入需要判断的字符串存放在数组中
2、将数组中的元素依次进栈
3、栈顶元素出栈与数组元素比较
效果相当于
a[3]
a[0]与a[2]比较
a[1]与a[1]比较
a[2]与a[0]比较
代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1024
#define n 1024
typedef char elem;
typedef struct SqStack
{
elem data[MAXSIZE];
int top;
}SqStack;
int Init_SqStack(SqStack *&S)
{
S = (SqStack*)malloc(sizeof(SqStack));
if(S == NULL)
{
printf("申请分配空间失败\n");
return 0;
}
S -> top = -1;
return 1;
}
int Full_SqStack(SqStack *S)
{
if(S -> top == MAXSIZE -1)
{
return 1;
}
else
{
return 0;
}
}
int Empty_SqStack(SqStack *S)
{
if(S -> top == -1)
{
return 1;
}
else
{
return 0;
}
}
void Push_SqStack(SqStack *&S, elem e)
{
if(Full_SqStack(S) == 1)
{
printf("栈已满,不能进行进栈操作\n");
return;
}
S -> top++;
S -> data[S -> top] = e;
}
int Pop_SqStack(SqStack *S, elem &e)
{
if(Empty_SqStack(S) == 1)
{
printf("该栈是空栈, 无数据元素\n");
return 0;
}
e = S -> data[S -> top];
S -> top--;
return 1;
}
int Symmetry(elem a[])
{
elem e;
SqStack *S;
Init_SqStack(S);
for(int i = 0; a[i]; i++)
Push_SqStack(S, a[i]);
for(int i = 0; a[i]; i++)
{
Pop_SqStack(S, e);
if(a[i] != e)
return 0;
}
return 1;
}
int main()
{
printf("请输入需要判断的字符串\n");
elem a[n];
gets(a);
if(Symmetry(a))
{
printf("该字符串是回文\n");
}
else
{
printf("该字符串不是回文\n");
}
return 0;
}
如有错误,欢迎读者批评指正。
如有疑问,可在下方留言。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)