用栈来判断字符串是否回文

#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;

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值