数据结构练习:利用栈和队列的特性设计一个算法,用于判断一个字符串是否为回文,输出不对,用内存很大
// 利用栈和队列的特性设计一个算法,用于判断一个字符串是否为回文。
# include <stdio.h>
# include <stdlib.h>
# define OK 1
# define ERROR 0
typedef int Status;
typedef struct QNode{//链队列结点
char data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;//队尾
}LinkQueue;
LinkQueue Q;
Status InitQueue(LinkQueue *Q){
Q->front = Q->rear = (QNode*)malloc(sizeof(QNode));
Q->front->next = NULL;
return OK;
}
Status EnQueue(LinkQueue *Q,char e){
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
p->data = e;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
return OK;
}
Status DeQueue(LinkQueue *Q,char *e){
QueuePtr p;
if(Q->front == Q->rear) return ERROR;
p = Q->front->next;
*e = p->data;
Q->front->next = p->next;
if(Q->rear == p)Q->rear = Q->front;
free(p);
return OK;
}
typedef struct{
char *base;
char *top;
int stacksize;
}Sqstack;
Sqstack S;
Status InitStack(Sqstack *S){
S->base = (char*)malloc(10*sizeof(char));
S->top = S->base;
S->stacksize = 10;
return OK;
}
Status Push(Sqstack *S,char e){
S->top++;
*S->top = e;
return OK;
}
Status Pop(Sqstack *S,char *e){
if(S->top == S->base)return ERROR;
*e = *--S->top;
return OK;
}
Status StackEmpty(Sqstack *S){
if(S->top==S->base){
return 0;
}else{
return 1;
}
}
int main(){
char ch;
char e;
int j=0;
InitStack(&S);
InitQueue(&Q);
while((ch=getchar())!='\n'){
scanf("%c",&ch);
Push(&S,ch);
EnQueue(&Q,ch);
}
while(StackEmpty(&S)){
char s,q;
Pop(&S,&s);
DeQueue(&Q,&q);
if (s==q){
j = 1;
}else{
j = 0;
break;
}
}
if(j==1){
printf("是回文");
}else{
printf("不是回文");
}
return 0;
}
输入abcba型回文以及不回文字符串时,按两次回车才输出不是回文,内存占用大,输入abccba时按一次回车输出不是回文
编译无警告,应该是哪里逻辑错了
想得到正确输出