7-1 回文判断 PTA

回文是指正读反读均相同的字符序列,如“abba”和“abdba”均是回文,但“good”不是回文。编写一个程序,使用栈判定给定的字符序列是否为回文。

输入格式:

输入待判断的字符序列,按回车键结束,字符序列长度<20。

输出格式:

若字符序列是回文,输出“YES”;否则,输出“NO”。

输入样例:

abdba

输出样例:

YES

利用c++内的stack来实现回文判断: 

#include <iostream>
#include <stack>
#include <string.h>
using namespace std;

int main()
{
	char sentence[20];
	int length;
	stack<char> s;
	
	//gets(sentence);
	cin>>sentence;
	length=strlen(sentence);
	
	for(int i=0;i<length/2;i++)
	{
		s.push(sentence[i]);
	}
	
	for(int i=length/2;i<length;i++)
	{
		if(s.top()==sentence[i])
		{
			s.pop();
		}
	}
	
	if(s.empty()==1)
	{
		cout<<"YES";
	}else cout<<"NO";
	
	
	return 0;
}

 以下是自定义顺序栈的代码演示:

#include <iostream>
#include <cstring>
#include <malloc.h>
#define STACK_INIT_SIZE 20
using namespace std;

typedef struct{
	char *base;
	char *top;
	int satcksize;
}sqStack;

void initStack(sqStack &s)
{
	if(!(s.base=(char*)malloc(STACK_INIT_SIZE*sizeof(char))))
		exit(1);
	s.top=s.base;
	s.satcksize=STACK_INIT_SIZE;
} 

void push(sqStack &s,char e)
{
	*(s.top) ++= e;
}

void pop(sqStack &s,char &e)
{
	if(s.base==s.top) return;
	e = *--s.top;
}

int huiwen(char *p)
{
	sqStack s;
	int flag=1;
	int i=1,j,len;
	initStack(s);
	len=strlen(p);
	while(i<=len/2)
	{
		push(s,*p);
		i++;
		*p++;   //*p++与p++ 
	}
	if(len%2==1) *p++; 
	for(j=i-1;j>=1;j--)
	{
		char a;
		pop(s,a);
		if(*p==a) *p++;
		else flag=0;
	}
	
	return flag;
}

int main()
{
	char p[21];
	cin>>p;
	if(huiwen(p)==1)
		cout<<"YES";
	else cout<<"NO";
	
	return 0;
}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亮子i_12138

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值