c语言实现队列和栈的方法
发布网友
发布时间:2022-04-20 04:51
我来回答
共1个回答
热心网友
时间:2022-04-06 11:18
#define OVERFLOW -1
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define N 20
typedef char SElemType;
typedef int Status;typedef struct {
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;#include<stdio.h>
#include<stdlib.h>Status CreatStack(SqStack &S){
//创建栈
S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S.base)exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}//CreatStackStatus Push(SqStack &S,SElemType e){
//插入e为新的栈顶元素
if(S.top-S.base>=S.stacksize){//栈满,追加存储空间
S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base)exit (OVERFLOW);//存储空间分配失败
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}//PushStatus Pop(SqStack &S ,SElemType &e){
//若栈不空,删除栈顶元素,并用e返回其值
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}//Pop typedef char QElemType;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QNodePtr;typedef struct{
QNodePtr front;
QNodePtr rear;
}LinkQueue;Status CreatQueue(LinkQueue &Q){
//建立一个空的链式栈
Q.front=Q.rear=(QNodePtr)malloc(sizeof(QNode));
if(!Q.front)exit(OVERFLOW);
Q.front->next=NULL;
return OK;
}Status EnQueue(LinkQueue &Q,QElemType e){ QNodePtr p;
p=(QNodePtr)malloc(sizeof(QNode));
if(!p)exit(OVERFLOW);
p->data=e;p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return OK;
}Status DeQueue(LinkQueue &Q,QElemType &e){QNodePtr p;<br>if(Q.front==Q.rear) return ERROR;<br>p=Q.front->next; e=p->data;<br>Q.front->next=p->next;<br>if(Q.rear==p) Q.rear=Q.front;<br>free(p);<br>return OK;<br>}int stackPalindrom_Test()//判别输入的字符串是否回文序列,是则返回1,否则返回0
{
printf("栈练习,请输入要判断的字符串以#作为结束符,不要超过二十个字符\n");
SqStack S;
CreatStack(S);
char c;
SElemType a;
SElemType b[N];
int count = 0;
fgets( b, N, stdin );
while((b[count])!='#')
{
Push(S,b[count]); //进栈
count++;
}
int i = 0;
while(i < count)
{
Pop(S,a);
if(a!=b[i])
return ERROR;
i++;
}
return OK;}//stackPalindrom_Test int queuePalindrom_Test()//判别输入的字符串是否回文序列,是则返回1,否则返回0
{
printf("队列练习,请输入要判断的字符串以#作为结束符,不要超过二十个字符\n");
LinkQueue Q;
CreatQueue(Q); char c;
SElemType a;
SElemType b[N];
int count = 0;
fgets( b, N, stdin );
while((b[count])!='#')
{
EnQueue(Q,b[count]);; //入列
count++;
} while(count-- > 0)
{
DeQueue(Q,a);
if(a!=b[count])
return ERROR;
}
return OK;
}//queuePalindrom_Test Status main(){ if(stackPalindrom_Test()==1)
printf("是回文\n");
else printf("不是回文\n"); if(queuePalindrom_Test()==1)
printf("是回文\n");
else printf("不是回文\n");
return OK;
}