队列:先进先出
环形队列的时间复杂度:
(1)入队:O(1)
(2)出队:O(1)
1、头文件(queue.h)
#pragma once
//顺序队列:设计成环形队列
#define SIZE 10
typedef struct Queue
{
int elem[SIZE];//数据
int front;//队头指针:队列中第一个数据的下标
int rear;//队尾指针:队尾数据的下一个数据下标即当前可以存放数据的下标
}Queue,*PQueue;
//初始化
void InitQueue(PQueue pq);
//入队
bool Push(PQueue pq,int val);
//出队
bool Pop(PQueue pq,int *rtval);
//判空
bool IsEmpty(PQueue pq);
//获得队头
bool GetTop(PQueue pq,int *rtval);
//摧毁
void Destroy(PQueue pq);
2、源文件(queue.cpp)
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "queue.h"
//初始化
void InitQueue(PQueue pq)
{
assert(pq != NULL);
pq->front = 0;
pq->rear = 0;
}
//判满:内部函数
//浪费一个单元格用于区分满和空
static bool IsFull(PQueue pq)
{
return (pq->rear+1) % SIZE == pq->front;
}
//入队
bool Push(PQueue pq,int val)//O(1)
{
if(IsFull(pq))
{
return false;
}
pq->elem[pq->rear] = val;
pq->rear = (pq->rear+1)%SIZE;
return true;
}
//出队(获得队头并删除)
bool Pop(PQueue pq,int *rtval)//O(1)
{
assert(pq != NULL);
if(IsEmpty(pq))
{
return false;
}
*rtval = pq->elem[pq->front];
pq->front = (pq->front+1)%SIZE;
return true;
}
//判空
bool IsEmpty(PQueue pq)
{
return pq->front == pq->rear;
}
//获得队头但不删除
bool GetTop(PQueue pq,int *rtval)
{
assert(pq != NULL);
if(IsEmpty(pq))
{
return false;
}
*rtval = pq->elem[pq->front];
return true;
}
//摧毁
void Destroy(PQueue pq)
{
pq->front = pq->rear;
}
3、测试源文件(test.cpp)
#include <stdio.h>
#include "queue.h"
int main()
{
int i;
Queue p;
InitQueue(&p);
for(i = 0; i < 10;i++)
{
Push(&p,i);//入队
}
int tmp;
while(!IsEmpty(&p))
{
Pop(&p,&tmp);//出队
printf("%d\n",tmp);
}
return 0;
}
上述程序的运行结果: