法一:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
//为了节省空间,采用循环数组,用到循环加1
//非空时,front和rear指向端点元素
//所以rear初始化为0,front为1
//满的时候,一种情况是,front为1,rear为MAXSIZE-1,满足(queue->rear+2)%queue->capacity==queue->front
//满的时候,也可能rear,front均在中间,但均满足(queue->rear+2)%queue->capacity==queue->front
//满的时候,数组也有一个空没元素
//空的时候,(queue->rear+1)%queue->capacity==queue->front
struct queuerecord{
int front;
int rear;
int capacity;//数组容量
//int size;//当前元素个数 本来用来判断满没满,既然有了循环加1,就不用了吧
int *data;
};
struct queuerecord* CreateAndInit(struct queuerecord* queue)
{
queue=(struct queuerecord *)malloc(sizeof(struct queuerecord));
queue->front=1;
queue->rear=0;
queue->capacity=MAXSIZE;
//queue->size=0;
queue->data=(int *)malloc(sizeof(int)*MAXSIZE);
return queue;
}
void Enqueue(struct queuerecord * queue,int number)
{
if((queue->rear+2)%queue->capacity==queue->front){
printf("The queue is full\n");
return;
}
//queue->size++;
queue->rear=(queue->rear+1)%queue->capacity;
queue->data[queue->rear]=number;
return;
}
void Dequeue(struct queuerecord* queue)
{
if((queue->rear+1)%queue->capacity==queue->front){
printf("The queue is empty\n");
return;
}
queue->front=(queue->front+1)%queue->capacity;
return;
}
int main()
{
struct queuerecord *queue;
queue=CreateAndInit(queue);
for(int i=1;i<=10;i++)
Enqueue(queue,i);
for(int i=1;i<=3;i++)
Dequeue(queue);
printf("%d %d\n",queue->front,queue->rear);
for(int i=queue->front;i<=queue->rear;i=(i+1)%MAXSIZE)
printf("%d ",queue->data[i]);
return 0;
}
法二:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
//为了节省空间,采用循环数组,用到循环加1
//非空时,front指向端点元素,rear指向端点的下一个位置,rear处无元素
//所以rear初始化为0,front为0
//满的时候,一种情况是,front为0,rear为MAXSIZE-1,满足(queue->rear+1)%queue->capacity==queue->front
//满的时候,也可能rear,front均在中间,但均满足(queue->rear+1)%queue->capacity==queue->front
//满的时候,数组也有一个空没元素
//空的时候,queue->rear==queue->front
struct queuerecord{
int front;
int rear;
int capacity;//数组容量
//int size;//当前元素个数 本来用来判断满没满,既然有了循环加1,就不用了吧
int *data;
};
struct queuerecord* CreateAndInit(struct queuerecord* queue)
{
queue=(struct queuerecord *)malloc(sizeof(struct queuerecord));
queue->front=0;
queue->rear=0;
queue->capacity=MAXSIZE;
//queue->size=0;
queue->data=(int *)malloc(sizeof(int)*MAXSIZE);
return queue;
}
void Enqueue(struct queuerecord * queue,int number)
{
if((queue->rear+1)%queue->capacity==queue->front){
printf("The queue is full\n");
return;
}
//queue->size++;
queue->data[queue->rear]=number;//先进新元素再更改rear
queue->rear=(queue->rear+1)%queue->capacity;
return;
}
void Dequeue(struct queuerecord* queue)
{
if(queue->rear==queue->front){
printf("The queue is empty\n");
return;
}
queue->front=(queue->front+1)%queue->capacity;
return;
}
int main()
{
struct queuerecord *queue;
queue=CreateAndInit(queue);
for(int i=1;i<=10;i++)
Enqueue(queue,i);
for(int i=1;i<=3;i++)
Dequeue(queue);
printf("%d %d\n",queue->front,queue->rear);
for(int i=queue->front;i<queue->rear;i=(i+1)%MAXSIZE)
printf("%d ",queue->data[i]);
return 0;
}