用队列和栈的功能实现回文的判定

来源:互联网 发布:什么是云计算和云服务 编辑:程序博客网 时间:2024/05/16 11:36

#include"stdio.h"
#include"stdlib.h"
#define STACKINCREMENT 10
#define STACK_INIT_SIZE 100

struct QNode
{
 char  data;
 struct QNode *next;
}QNode;
struct linkQueue
{
 struct QNode * front;
 struct QNode * rear;
}linkQueue;//队列

struct SqStack
{
 char * base;
 char * top;
 int stacksize;
}Sqstack;//堆栈

int InitStack(SqStack &S)
{
 S.base=(char *)malloc(STACK_INIT_SIZE *sizeof(char));
 if(!S.base)
  printf("内存分配失败!");
 S.top=S.base;
 S.stacksize=STACK_INIT_SIZE;
 return 0;
}//构建一个空栈

int Push(SqStack &S,char e)
{
 if(S.top-S.base>=S.stacksize)
 {
  S.base=(char*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(char));
  if(!S.base)
   printf("内存分配失败!");
  S.top=S.base+S.stacksize;
  S.stacksize+=STACKINCREMENT;
 }
 *S.top++=e;
 return 0;
}//输入一个元素进栈

char Pop(SqStack &S)
{
 char e;
 if(S.top==S.base)
  printf("堆栈为空");
 e= * --S.top;
 return e;
}//元素出栈

int InitQueue(struct linkQueue &Q)
{
 Q.front=Q.rear=(struct QNode *)malloc(sizeof(QNode));
 if(!Q.front)
  printf("内存分配失败!");
 Q.front->next=NULL;
 return 0;
}//构建一个空队列

int EnQueue(struct linkQueue &Q,char e)
{
 struct QNode * p;
 p=(struct QNode *)malloc(sizeof(QNode));
 if(!p)
  printf("内存分配失败!");
 p->data=e;
 p->next=NULL;
 Q.rear->next=p;
 Q.rear=p;
 return 0;
}//插入一个元素到队列中

char DeQueue(struct linkQueue &Q)
{
 char e;
 struct QNode * p;
 if(Q.front==Q.rear)
  printf("队列为空!");
 p=Q.front->next;
 e=p->data;
 Q.front->next=p->next;
 if(Q.rear==p)
  Q.rear=Q.front;
 free(p);
 return e;
}//删除队列中的元素

int main()
{
 char c;
 struct SqStack s;
 struct linkQueue q;
 InitStack(s);
 InitQueue(q);
 printf("请输入一串字符,以#号结束!");
 scanf("%c",&c);
 while(c!='#')
 {
  Push(s,c);
  EnQueue(q,c);
  scanf("%c",&c);
 }
 while(!(s.top==s.base))
 
  if(Pop(s)!=DeQueue(q))
  {
   printf("这个字符串不是回文!\n");
   exit(0);  
  }
 }
 printf("这个字符串是回文!\n"); 
 return 0;
}

 


 

原创粉丝点击