利用順序棧判斷一個字符串是否是對稱串
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
#define MaxSize 60
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top; //棧頂指針
}SqStack; //定義順序棧類型
//初始化棧
void InitStack(SqStack *&s){
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-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++; //指針加一
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--; //指針減一
return true;
}
//判斷一個字符串是否是對稱串
bool symmetry(string str){
ElemType e;
SqStack *st;
InitStack(st); //初始化棧
//元素進棧
for(int i=0;i<str.length();i++){
Push(st,str[i]);
}
//比較棧中元素和字符串
for(int i=0;i<str.length();i++){
Pop(st,e); //出棧,e存放的是當前棧頂元素
if(e!=str[i]){ //不同
DestroyStack(st); //銷燬棧
return false;
}
}
DestroyStack(st);
return true;
}
int main(){
string str;
cout<<"str:";
cin>>str;
bool flag;
//判斷它是不是對稱串
flag=symmetry(str);
if(flag)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}