队列可以有两种存储结构表示,顺序存储结构和链式存储结构,以下代码在DEV C++下编译运行通过。
/*循环队列的顺序存储结构*/
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
#include<windows.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 10
typedef int QElemType;
typedef int Status;
typedef struct
{
QElemType data[MAXSIZE];
int front;
int rear;
} SqQueue;
//初始化一个空队列Q
Status InitQueue(SqQueue *Q)
{
Q->front=0;
Q->rear=0;
return OK;
}
//返回Q的元素个数
int QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
//入队
Status EnQueue(SqQueue *Q,QElemType e)
{
if((Q->rear+1)%MAXSIZE==Q->front)
return ERROR;
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXSIZE;
return OK;
}
//出队
Status DeQueue(SqQueue *Q,QElemType *e)
{
if(Q->front==Q->rear)
return ERROR;
*e=Q->data[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return OK;
}
int main(){
SqQueue sqqueue;
InitQueue(&sqqueue);
QElemType e=123,ee;
EnQueue(&sqqueue,e);
printf("%d\n",QueueLength(sqqueue));
DeQueue(&sqqueue,&ee);
printf("%d\n",ee);
}
//队列的链式存储结构
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
#include<windows.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 10
typedef int QElemType;
typedef int Status;
typedef struct QNode
{
QElemType data;
struct QNode *next;
} QNode,*QueuePtr;
typedef struct
{
QueuePtr front,rear;
}LinkQueue;
Status EnQueue(LinkQueue *Q,QElemType e)
{
QueuePtr s=(QueuePtr)malloc(sizeof(QNode));
s->data=e;
s->next=NULL;
Q->rear->next=s;
Q->rear=s;
return OK;
}
Status DeQueue(LinkQueue *Q,QElemType *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;
}
int main(){
QNode qnode;
LinkQueue linkqueue;
linkqueue.front=&qnode;
linkqueue.rear=&qnode;
QElemType e=123,ee;
EnQueue(&linkqueue,e);
printf("%d\n",linkqueue.rear->data);
DeQueue(&linkqueue,&ee);
printf("%d\n",ee);
}