队列
1.循环队列
#include<stdio.h>
#define MAXSIZE 10
#define TRUE 1
#define FALSE 0
typedef struct
{
int data[MAXSIZE];
int front;
int rear;
}SqQueue;
int InitQueue(SqQueue *Q);
int QueueLength(SqQueue *Q);
int EnQueue(SqQueue *Q,int m);
int DeQueue(SqQueue *Q,int *e);
int main()
{
SqQueue queue;
int t;
InitQueue(&queue);
for(int i=0;i<MAXSIZE-1;++i)
{
EnQueue(&queue,i);
}
DeQueue(&queue,&t);
printf("%d\n",t);
return 0;
}
int InitQueue(SqQueue *Q)
{
Q->front=0;
Q->rear=0;
return TRUE;
}
int QueueLength(SqQueue *Q)
{
return (Q->rear-Q->front+MAXSIZE)%MAXSIZE;
}
int EnQueue(SqQueue *Q,int m)
{
if((Q->rear+1)%MAXSIZE==Q->front)
return FALSE;
Q->data[Q->rear]=m;
Q->rear=(Q->rear+1)%MAXSIZE;
return TRUE;
}
int DeQueue(SqQueue *Q,int *e)
{
if(Q->front==Q->rear)
return FALSE;
*e=Q->data[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return TRUE;
}
2.队列的链式存储结构
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct QNODE
{
int data;
QNODE *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int InitQueue(LinkQueue *Q);
int EnQueue(LinkQueue *Q,int m);
int DeQueue(LinkQueue *Q,int *e); //error C2018: unknown character '0xa3' 因为分号用的是中文状态下的
int main()
{
LinkQueue queue;
QNode *p;
p=(QNode*)malloc(sizeof(QNode));
p->next=NULL;
queue.front=p;
queue.rear=p;
int e;
for(int i=0;i<10;++i)
{
EnQueue(&queue,i);
}
DeQueue(&queue,&e);
printf("%d\n",e);
return 0;
}
int EnQueue(LinkQueue *Q,int m)
{
QNode *p;
p=(QNode*)malloc(sizeof(QNode));
p->data=m;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
return TRUE;
}
int DeQueue(LinkQueue *Q,int *e)
{
if(Q->front==Q->rear)
return FALSE;
QNode *p;
p=Q->front->next;
*e=p->data;
Q->front->next=p->next;
if(Q->rear==p) //如果对头是队尾,则删除后将rear指向头结点
Q->rear=Q->front;
free(p);
return TRUE;
}