数据结构:用栈和队列判断是否回文c++

#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE  100   
#define STACKINCREMENT   10   
typedef char ElemType;  
#define MAXQSIZE 100   
typedef struct {
    ElemType *base;  
    int  front;                             
    int  rear;      
  } SqQueue;

typedef  struct
{  ElemType  *base;
   ElemType  *top;
   int  stacksize;  
 }SqStack;
 

SqStack InitStack(SqStack S)
{  S.base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
   if (!S.base) printf("空间分配失败\n"); 
   S.top=S.base;
   S.stacksize=STACK_INIT_SIZE;
   return S;
}

void Push(SqStack *S, ElemType e) 
{
  if (S->top-S->base>=S->stacksize) 
   {
       S->base = (ElemType *) realloc (S->base,(S->stacksize + STACKINCREMENT)*sizeof (ElemType));
       if (!S->base) printf("空间分配失败\n"); 
       S->top=S->base+S->stacksize;
       S->stacksize+=STACKINCREMENT;
   }
    *(S->top++) = e;  
    
 }

ElemType GetTop(SqStack *S)
{
  if ((*S).top==(*S).base) printf("栈是空的\n");
  ElemType e;
  e=*((*S).top-1);
  (*S).top--;
  return e;
 }  


SqQueue InitQueue (SqQueue Q) 
{   
    Q.base = (ElemType *) malloc(MAXQSIZE *sizeof (ElemType));
    if (!Q.base) printf("空间分配失败!\n");                             
    Q.front=0; 
	Q.rear=0;
	return Q;
 }
void EnQueue(SqQueue *Q,ElemType e) 
{   
    if (((*Q).rear+1) % MAXQSIZE==(*Q).front) 
    printf("队列已满!\n");   
	(*Q).base[(*Q).rear] = e;
    (*Q).rear = ((*Q).rear+1) % MAXQSIZE;
	
}
ElemType  DeQueue (SqQueue *Q) 
{	
    ElemType e;
	if (Q->front==Q->rear)  
		printf("队列空!\n");
    e=Q->base[Q->front];
    Q->front = (Q->front+1) % MAXQSIZE;
    return e;
}

void huiwen()
{  SqQueue Q,Q1;SqStack S,S1;
   Q1=InitQueue(Q);
   S1=InitStack(S);
   ElemType c;
   scanf("%c",&c);
   while(c!='#')
   {
       EnQueue(&Q1,c);
	   Push(&S1,c);
	   scanf("%c",&c);
   }
   while(Q1.front!=Q1.rear && S1.top!=S1.base)
	  { if(GetTop(&S1)==DeQueue(&Q1))
	       continue;		   
           else { printf("不是回文!\n");break;}}
   if(Q1.front==Q1.rear && S1.top==S1.base)
        printf("是回文!\n");

}
void main()
{
   printf("请输入字符串,以'#'结束!\n");
   huiwen();
}

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值