内容:
回文是指正读和反读均相同的字符序列,试写一个算法判定给定的字符向量是否为回文。
1.算法分析
程序中设计了四个函数:
函数Init_SeqStack用来初始栈
函数IsHuiwen用来实现回文的判断
回文判断问题需要用到栈的基本操作,一半字符入栈与另一半进行对比。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define StackSize 100
typedef char DataType;
typedef struct {
DataType data[StackSize];
int top;
}SeqStack;
int Init_SeqStack(SeqStack*& S)
{
S = (SeqStack*)malloc(sizeof(SeqStack));//申请空间
if (S == NULL)
{
printf("申请分配空间失败\n");
return 0; //失败返回0
}
S->top = -1; //将-1赋值给栈顶指针
return 1;
}
int IsHuiwen(char* t)
{
int i, b, len;
SeqStack* S;
Init_SeqStack(S);
char temp;
len = strlen(t);
for (i = 0; i < len / 2; i++)
{
if (S->top < StackSize - 1)
S->data[++S->top] = t[i];
else
{
printf("栈满溢出");
exit;
}
}
if (len % 2 == 1)i++;
while (S->top > -1)
{
temp = S->data[S->top--];
if (temp != t[i])
return 0;
else
i++;
}
return 1;
}
int main()
{
printf("请输入需要判断的字符串\n");
DataType data[StackSize];
scanf_s("%s", data, 50);
if (IsHuiwen(data))
{
printf("该字符串是回文\n");
}
else //否则执行printf("该字符串不是回文\n");
{
printf("该字符串不是回文\n");
}
return 0;
}
2.效果图