版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目:回文是指正读反读均相同的字符序列,如“abba”、“abdba”均是回文,但“good”不是回文。
思想:字符数为偶数时,前半部分入栈,后半部分入队;字符为奇数时,用getchar接收中间的字符,其余的按偶数处理。
代码如下:
#include<iostream>
#define MaxSize 100
#define OK 1
#define ERROR 0
using namespace std;
typedef char ElemType;
typedef int Status;
typedef struct StackNode/*栈*/
{
ElemType data;
struct StackNode *next;
}StackNode, *LinkStack;
/*队列*/
typedef struct
{
ElemType *base;
int front;
int rear;
}SqQuene;
Status InitQueue(SqQuene &Q)/*队列的初始化*/
{
Q.base = new ElemType[MaxSize];
Q.front = Q.rear = 0;
return OK;
}
Status InitStack(LinkStack &S)/*栈的初始化*/
{
S = NULL;
return OK;
}
Status Push(LinkStack &S, ElemType e)/*入栈*/
{
LinkStack p;
p = new StackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
Status EnQueue(SqQuene &Q, ElemType e)/*入队*/
{
if ((Q.rear + 1) % MaxSize == Q.front)return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MaxSize;
return OK;
}
ElemType Pop(LinkStack &S)/*弹出栈顶元素*/
{
ElemType e;
LinkStack p;
e = S->data;
p = S;
S = S->next;
delete p;
return e;
}
ElemType DeQuenue(SqQuene &Q)/*出队*/
{
ElemType e;
if (Q.front == Q.rear)return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return e;
}
Status StackEmpty(LinkStack S)/*判断是否栈空,是返回1,否返回0*/
{
if (S == NULL)return OK;
else
return ERROR;
}
ElemType GetHead(SqQuene Q)
{
return Q.base[Q.front];
}
Status GetTop(LinkStack S)/*获取栈顶元素的值,不修改指针*/
{
if (S != NULL)return S->data;
return OK;
}
void PrintStack(LinkStack S)/*输出栈里的元素*/
{
LinkStack p;
p = S;
while (p)
{
cout << p->data << " ";
p = p->next;
}
}
Status MatchingStack(LinkStack &S)/*匹配栈的栈顶元素和队列的队头*/
{
return OK;
}
int main()
{
ElemType CH;
int num,flag=0;
LinkStack S;
SqQuene Q;
InitStack(S);/*栈的初始化*/
InitQueue(Q);/*队列的初始化*/
cout << "请输入字符串的长度:";
cin >> num;
if (num % 2 == 0)
{
for (int i = 0; i < num / 2; i++)
{
cin >> CH;
Push(S, CH);/*入栈*/
}
for (int i = 0; i < num / 2; i++)
{
cin >> CH;
EnQueue(Q, CH);/*入队*/
}
}
if (num % 2 == 1)
{
for (int i = 0; i < num / 2; i++)
{
cin >> CH;
Push(S, CH);/*入栈*/
}
getchar();
for (int i = 0; i < num / 2; i++)
{
cin >> CH;
EnQueue(Q, CH);/*入队*/
}
}
//int count = 0;
ElemType e,f;
while (!StackEmpty(S))
{
//count++;
e = Pop(S);
f = DeQuenue(Q);
//cout << e<<endl;
//cout << f << endl;
if (e == f)
flag = 1;
else
{
flag = 0;break;
}
}
if (flag)cout << "是回文" << endl;
else
cout << "不是回文" << endl;
//cout << count;
system("pause");
return 0;
}
(ps:方法很麻烦)