假设称正读和反读都相同的字符序列为“回文”,例如,‘abba’和‘abcba’是回文,‘abcde’和‘ababab’则不是回文。试写一个算法判别读入的一个以‘@’为结束符的字符序列是否是“回文”。
输入一个以@结尾的字符序列,判断该字符序列是否为回文输出:abba是回文或abcba不是回文;
输入:abcba@
输出:abcba是回文
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define Error 0
#define STACK_INTT_SIZE 100
#define STACKINCRAMENT 10
typedef int status;
typedef char Selemtype;
typedef char Qelemtype;
typedef struct {
Selemtype* top;
Selemtype* base;
int stacksize;
}SqStack;
typedef struct Qnode{
Qelemtype date;
struct Qnode* next;
}Qnode, * Queueprt;
typedef struct {
Queueprt front;
Queueprt rear;
}LinkQueue;
//创建一个空栈
status InitStack(SqStack& S) {
S.base = 0;
S.base = (Selemtype*)malloc(STACK_INTT_SIZE * sizeof(Selemtype));
if (!S.base)
return Error;
S.top = S.base;
S.stacksize = STACK_INTT_SIZE;
return OK;
}
//创建一个空队列
status InitQueue(LinkQueue &Q) {
Q.front = Q.rear = (Queueprt)malloc(sizeof(Qnode));
if (!Q.front)
return Error;
Q.front->next = NULL;
return OK;
}
//将元素e插入栈的顶部
status Push(SqStack& S, Selemtype e) {
if (S.top - S.base >= S.stacksize)
{
S.base = (Selemtype*)realloc(S.base, (STACKINCRAMENT + STACK_INTT_SIZE) * sizeof(Selemtype));
if (!S.base)
return Error;
S.top = S.base + S.stacksize;
S.stacksize += STACKINCRAMENT;
}
*S.top = e;
S.top++;
return OK;
}
//将元素e插入队列尾部
status EnElem(LinkQueue& Q, Qelemtype e) {
Queueprt p;
p = (Queueprt)malloc(sizeof(Qnode));
if (!p)
return Error;
p->date = e;
p->next = Q.rear->next;
Q.rear->next = p;
Q.rear = p;
return OK;
}
//输出栈的顶部元素并用e返回
Selemtype Pop(SqStack& S, Selemtype& e) {
if (S.base ==S.top)
return Error;
e = *--S.top;
return e;
}
//输出队列的头部元素
Qelemtype Getelem(LinkQueue& Q, Qelemtype& e) {
if (Q.front == Q.rear)
return Error;
Queueprt q;
q= Q.front->next;
e =q->date;
Q.front->next = q->next;
free(q);
return e;
}
//判断栈是否为空
status IS_SqStack(SqStack S) {
if (S.base == S.top)
return Error;
else
return OK;
}
//判断队列是否为空
status IS_Linkqueue(LinkQueue Q) {
if (Q.front == Q.rear)
return Error;
else
return OK;
}
int main() {
int n = 0;
SqStack S;
LinkQueue Q;
Selemtype num1;
Qelemtype num2;
InitStack(S);
InitQueue(Q);
/* char ch;
ch = getchar();
do {
Push(S, ch);
EnElem(Q, ch);
rewind(stdin);//getchar和scanf输入后以回车结尾,需要消除这个字符,否则下一次提取就会提取回车键,而不会提取输入的字符
ch = getchar();
} while (ch != '@');
while (IS_SqStack(S)&&IS_Linkqueue(Q)){
Pop(S, num1);
Getelem(Q, num2);
putchar(num2);
if (num1 != num2) {
n++;
}
}*///使用这种方法输入,在输入一个字符后需要加回车输入下一个字符,与题意不符
char ch[20] = {0};
int i = 0;
while ((ch[i++] = getchar()) != '@');
for (int i = 0;ch[i]!='@'; i++) {
Push(S, ch[i]);
EnElem(Q, ch[i]);
}
while (IS_SqStack(S) && IS_Linkqueue(Q)) {
Pop(S, num1);
Getelem(Q, num2);
putchar(num2);
if (num1 != num2) {
n++;
}
}
if (n == 0)
printf("是回文");
else
printf("不是回文");
return 0;
}