#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define MAX_SIZE 100
class Stack
{
private:
char *data;
int top;
public:
Stack();//构造函数
~Stack();//析构函数
void Push(int a);//压栈,即将字符放进栈中
char Pop();//出栈,将字符串弹出栈
//int GetTop();
bool IsFull();//判断栈是否满
bool IsHui(char str[]);//判断是否回文
bool IsEmpty();//判断栈是否为空
};
Stack::Stack()//
{
data=new char[MAX_SIZE];
top=-1;//
}
Stack::~Stack()//
{
delete[] data;
}
bool Stack::IsFull()
{
if(top==MAX_SIZE-1)
return true;
else
return false;
}
/*
int Stack::GetTop()//该函数对此题作用不大,故注释掉
{
while(!IsFull())
{
top++;
}
int t=top;
return t;
}*/
void Stack::Push(int a)//
{
if(!IsFull())
data[++top]=a;
}
char Stack::Pop()//
{
char x;
if(!IsFull())
{
x=data[top--];
}
return x;
}
bool Stack::IsEmpty()
{
if(top==-1)
return true;
else
return false;
}
bool Stack::IsHui(char str[])
{
int len=strlen(str);//字符串的长度
//cout<<len;
Stack a;//定义一个对象,才能使用函数
if(len%2==0)//长度为偶
{
for(int i=0;i<len/2;i++)
{
a.Push(str[i]);//先压一半字符
}
for(int j=len/2;j<len;j++)
{
char c=a.Pop();//再一个个弹出
if(c!=str[j])//与后面的一一比对
return false;
}
}
else//为奇数时与偶数相似,但是居中的不比对
{
for(int i=0;i<len/2;i++)
{
a.Push(str[i]);
}
for(int j=len/2+1;j<len;j++)//居中的不比对
{
char c=a.Pop();
if(c!=str[j])
return false;
}
}
return true;
}
int main()
{
class Stack *p=new Stack();//定义一个指针对象
char a[20];
cin>>a;
if(!p->IsHui(a))
{
cout<<"NO";
}
else
{
cout<<"YES";
}
delete[] p;
}
用栈来判断字符串是否回文
最新推荐文章于 2024-04-25 08:31:40 发布