C语言队列
队列的定义和初始化
结构体里包括,队头指针,队尾指针,队列的容量和数组。
初始化队列需要将队头指针和队尾指针都设置为一个特殊值。
typedef struct Queue
{
int front, rear;
int maxsize;
int* data;
}Queue;
//初始化队列
void Init(Queue* queue)
{
queue->maxsize = MAX_SIZE;
queue->data = (int*)malloc(sizeof(int) * queue->maxsize);
queue->front = -1;
queue->rear = -1;
}
判断队列是否为空
当队头指针为设定特殊值时,说明现在队列为空
//判断队列是否为空
int Empty(Queue* queue)
{
if (queue->front == -1)
{
return 1;
}
return 0;
}
判断队列是否满
判断队头指针是否和队尾指针相等,相等则是队满。
//判断队列是否满
int Full(Queue* queue)
{
if ((queue->rear)%queue->maxsize==queue->front)
{
return 1;
}
return 0;
}
队列的入队操作
//入队操作
void EnQueue(Queue* queue, int num)
{
if (Empty(queue))
{
queue->front = 0;
queue->rear = 1;
queue->data[queue->front] = num;
}
else if (!Full(queue))
{
queue->data[queue->rear] = num;
queue->rear=(queue->rear+1)%queue->maxsize;
}
}
出队操作
//出队操作
int DeQueue(Queue* queue)
{
if (!Empty(queue))
{
int i = queue->front;
queue->front = (queue->front + 1) % queue->maxsize;
if (queue->front == queue->rear)
{
queue->front = -1;
queue->rear = -1;
}
return queue->data[i];
}
return - 1;
}
获取队头元素
//获取队头元素
int Front(Queue* queue)
{
if (!Empty(queue))
{
return queue->data[queue->front];
}
return -1;
}
清空队列
void Clear(Queue* queue)
{
while(!Empty(queue))
{
DeQueue(queue);
}
}
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <malloc.h>
#define MAX_SIZE 10
typedef struct Queue
{
int front, rear;
int maxsize;
int* data;
}Queue;
//初始化队列
void Init(Queue* queue)
{
queue->maxsize = MAX_SIZE;
queue->data = (int*)malloc(sizeof(int) * queue->maxsize);
queue->front = -1;
queue->rear = -1;
}
//判断队列是否为空
int Empty(Queue* queue)
{
if (queue->front == -1)
{
return 1;
}
return 0;
}
//判断队列是否满
int Full(Queue* queue)
{
if ((queue->rear)%queue->maxsize==queue->front)
{
return 1;
}
return 0;
}
//入队操作
void EnQueue(Queue* queue, int num)
{
if (Empty(queue))
{
queue->front = 0;
queue->rear = 1;
queue->data[queue->front] = num;
}
else if (!Full(queue))
{
queue->data[queue->rear] = num;
queue->rear=(queue->rear+1)%queue->maxsize;
}
}
//出队操作
int DeQueue(Queue* queue)
{
if (!Empty(queue))
{
int i = queue->front;
queue->front = (queue->front + 1) % queue->maxsize;
if (queue->front == queue->rear)
{
queue->front = -1;
queue->rear = -1;
}
return queue->data[i];
}
return - 1;
}
//获取队头元素
int Front(Queue* queue)
{
if (!Empty(queue))
{
return queue->data[queue->front];
}
return -1;
}
void Clear(Queue* queue)
{
while(!Empty(queue))
{
DeQueue(queue);
}
}
void print1(Queue* queue)
{
int i = (queue->front+1)%queue->maxsize;
printf("%d ", queue->data[queue->front]);
while(i!= queue->rear)
{
printf("%d ", queue->data[i]);
i = (i + 1) % queue->maxsize;
}
printf("\n");
}
void print(Queue* queue)
{
printf("%d\n", Front(queue));
}
int main()
{
Queue queue;
Init(&queue);
EnQueue(&queue, 1);
EnQueue(&queue, 2);
EnQueue(&queue, 3);
EnQueue(&queue, 4);
EnQueue(&queue, 5);
print(&queue);
print1(&queue);
DeQueue(&queue);
print(&queue);
EnQueue(&queue, 7);
print1(&queue);
Clear(&queue);
print(&queue);
}