Problem B: 回文(栈和队列)
Description
假设称正读和反读都相同的字符序列为“回文”,例如,‘abba‘ 和 ‘abcba‘是回文,‘abcde‘ 和 ‘ababab‘ 则不是回文。试写一个算法判别读入的一个以‘@‘为结束符的字符序列是否是“回文”。
Input
abcba
Output
是回文
Sample Input
ababab
Sample Output
不是回文
HINT
判断是不是回文:
先将前一半个字符入栈,然后依次取出栈顶元素,判断是否相同如果相同则栈顶元素出栈,否则不是回文。
代码:
#include <iostream>
#include<string.h>
using namespace std;
struct node
{
char ch;
node *next;
} *head;
node* instack(char c)
{
node *p;
static int count1=0;
if(count1==0)
{
p=new node;
p->ch=c;
p->next=NULL;
count1++;
return p;
}
else
{
p=new node;
p->ch=c;
p->next=head;
return p;
}
}
void stack_pop()
{
node *p;
p=head;
head=head->next;
delete p;
}
char stack_top()
{
return head->ch;
}
bool stack_empty()
{
if(head==NULL)
return true;
return false;
}
int main()
{
int i,k;
char s[101],c;
bool YON=true;
while(cin>>s)
{
k=strlen(s);
for(i=0; i<k/2; i++)
{
head=instack(s[i]);//前1/2的字符入栈
}
for(i=(k%2==1?k/2+1:k/2);i<k;i++)//后面的和栈顶元素判断
{
if(!stack_empty())
{
c=stack_top();//取出栈顶元素
if(c==s[i])//如果相同则栈顶元素出栈
{
stack_pop();
}
else
{
YON=false;//否则输出置为假
break;
}
}
else
{
YON=false;
break;
}
}
if(YON)
cout<<"是回文"<<endl;
else
cout<<"不是回文"<<endl;
memset(s,'\0',sizeof(s));
}
return 0;
}