顺序表示
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
struct SeqQueue{
int MAXNUM;
int f,r;
DataType *q;
};
typedef struct SeqQueue *PSeqQueue;
PSeqQueue createEmptyQueue_seq(int m)
{
PSeqQueue paqueue = (PSeqQueue)malloc(sizeof(struct SeqQueue));
if(paqueue!=NULL)
{
paqueue->q = (DataType*)malloc(sizeof(DataType)*m);
if(paqueue->q ){
paqueue->MAXNUM = m;
paqueue->f = 0;
paqueue->r = 0;
return paqueue;
}
else free(paqueue);
}
printf("Out of space!!!\n");
return NULL;
}
int isNullQueue_seq(PSeqQueue paqueue)
{
return (paqueue->f == paqueue->r );
}
void enQueue_seq(PSeqQueue paqueue,DataType x)
{
if((paqueue->r+1)%paqueue->MAXNUM == paqueue->f)
printf("Full queue.\n");
else{
paqueue->q[paqueue->r] = x;
paqueue->r = (paqueue->r+1)%paqueue->MAXNUM ;
}
}
void deQueue_seq(PSeqQueue paqueue)
{
if(paqueue->f == paqueue->r)
printf("Empty Queue.\n");
else
paqueue->f =(paqueue->f+1)%paqueue->MAXNUM ;
}
DataType frontQueue_seq(PSeqQueue paqueue)
{
if(paqueue->f == paqueue->r )
printf("Empty Queue.\n");
else
return (paqueue->q[paqueue->f]);
}
void prin_queue(PSeqQueue paqueue)
{
int fir = paqueue->f;
int end = paqueue->r ;
int i=0;
for(i=fir;i<end;i++)
{
printf("%d ",paqueue->q[i]);
}
}
int main()
{
PSeqQueue paqueue = createEmptyQueue_seq(5);
int flag = isNullQueue_seq(paqueue);
enQueue_seq(paqueue,1);
enQueue_seq(paqueue,2);
enQueue_seq(paqueue,3);
enQueue_seq(paqueue,4);
enQueue_seq(paqueue,5);
deQueue_seq(paqueue);
DataType x = frontQueue_seq(paqueue);
prin_queue(paqueue);
return 0;
}
输出:
Full queue.
2 3 4
链接表示
#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node *PNode;
typedef int DataType;
struct Node{
DataType info;
PNode link;
};
struct LinkQueue{
PNode f;
PNode r;
};
typedef struct LinkQueue *PLinkQueue;
PLinkQueue createEmptyQueue_link(void)
{
PLinkQueue plqu;
plqu = (PLinkQueue)malloc(sizeof(struct LinkQueue));
if(plqu!=NULL)
{
plqu->f = NULL;
plqu->r = NULL;
}
else
printf("Out of space!!\n");
return plqu;
}
int isEmptyQueue_link(PLinkQueue plqu)
{
return(plqu->f == NULL);
}
void enQueue_link(PLinkQueue plqu,DataType x)
{
PNode p;
p = (PNode)malloc(sizeof(struct Node));
if(p==NULL)printf("Out of space!!\n");
else{
p->info = x;
p->link = NULL;
if(plqu->f ==NULL)plqu->f = p;
else plqu->r->link = p;
plqu->r = p;
}
}
void deQueue_link(PLinkQueue plqu)
{
PNode p;
if(plqu->f == NULL)printf("Empty queue.\n");
else{
p = plqu->f;
plqu->f = p->link;
free(p);
}
}
DataType frontQueue_link(PLinkQueue plqu)
{
if(plqu->f == NULL)printf("Empty queue.\n");
else return(plqu->f->info );
}
void prin_link(PLinkQueue plqu)
{
PNode fir = plqu->f;
PNode end = plqu->r;
while(fir!=NULL)
{
printf("%d ",fir->info);
fir = fir->link ;
}
}
int main()
{
PLinkQueue plqu;
plqu = createEmptyQueue_link();
int flag = isEmptyQueue_link(plqu);
enQueue_link(plqu,1);
enQueue_link(plqu,2);
enQueue_link(plqu,3);
enQueue_link(plqu,4);
enQueue_link(plqu,5);
deQueue_link(plqu);
prin_link(plqu);
return 0;
}
输出:
2 3 4 5