#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef struct {
ElemType data[MaxSize]; //存放栈中的数据元素
int top; //栈顶指针,即存放栈顶元素在data数据中的下标
}SqStack; //顺序栈类型
//================================初始化栈
void InitStack(SqStack*& s) {
s = (SqStack*)malloc(sizeof(SqStack)); //分配一个顺序栈空间,首地址存放在s中
s->top = -1; //栈顶指针置为-1
}
//================================销毁栈
void DestroyStack(SqStack*& s) {
free(s);
}
//================================判断栈是否为空
bool StackEmpty(SqStack* s) {
return(s->top == -1);
}
//=================================进栈
bool Push(SqStack*& s, ElemType e) {
if (s->top == MaxSize - 1) //栈满的情况,即栈上溢出
return false;
s->top++; //栈顶指针增1
s->data[s->top] = e;
return true;
}
//=================================出栈
bool Pop(SqStack*& s, ElemType& e) {
if (s->top == -1) //栈为空,即栈下溢出
return false;
e = s->data[s->top]; //取栈顶元素
s->top--; //栈顶指针减1
return true;
}
//==================================取栈顶元素
bool GetTop(SqStack* s, ElemType& e) {
if (s->top == -1) //栈为空,即栈下溢出
return false;
e = s->data[s->top]; //取栈顶元素
return true;
}
//===================判断一个字符串str是否为对称串=================================================
bool symmetry(ElemType str[]) {
int i;
ElemType e;
SqStack* st; //定义顺序栈指针
InitStack(st); //初始化栈
for (i = 0; str[i] != '\0'; i++) //将str的所有元素进栈
Push(st, str[i]);
for (i = 0; str[i] != '\0'; i++) { //处理str的所有字符
Pop(st, e); //退栈元素e
if (str[i] != e) //若e与当前串字符不同,表示不是对称串
{
DestroyStack(st); //销毁栈
return false; //返回假
}
}
DestroyStack(st); //销毁栈
return true; //返回真
}
int main() {
char str[5] = "abba";
bool result=symmetry(str);
if (result == 1) {
printf("true");
}
else {
printf("false");
}
return 0;
}
c语言之判断一个字符串是否为对称串
最新推荐文章于 2023-07-22 20:06:37 发布