顺序栈之判断一个字符串是否是对称串

问题设计:

设计一个算法利用顺序栈判断一个字符串是否是对称串。所谓对称串是指从左向右读和从右向左读的序列相同。

代码实现:

#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;
   cin>>str;
   bool flag;
   //判断它是不是对称串
   flag=symmetry(str);
   if(flag)
	   cout<<str<<"是回文串"<<endl;
   else
	   cout<<str<<"不是回文串"<<endl;
}

运行结果:

经验分享 程序员 微信小程序 职场和发展