队列是一种线性表,他遵循的规则是先进先出,就好比我们排队买票一样。队列的顺序结构,我们可以用一个数组来表示一个队列,设置一个表示表头坐标的变量和一个表尾坐标的变量,读取一个元素的时候,表头坐标后移一位。添加一个元素的时候表尾元素加一位。当表尾大于数组的长度的时候就溢出了。有一种情况,当表头指针后移几位,表尾指针刚好大于数组长度的时候,数组中被取出的数据的空间没用到,称为“假溢出”。为了合理利用空间,我们可以把队列看做是环形的,我们可以用模运算来解决这一问题。
判断队列满的条件,用rear尾指针-front头指针==数组长度,判断队列是否为空的条件就是:rear尾指针==front头指针。每插入一个数据frear做一次假发运算,每取一次数据front做一次加法运算。
代码:
// 队列的链式存储.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#define SIZE 5 //队列的长度
struct queue
{
int *element;
int front;
int rear;
};
int isEmpty(queue *q) //判断队列是否为空
{
if(q->front>q->rear)
return 1;
return 0;
}
int isFull(queue *q) //判断队列空间是否满了
{
if(q->rear-q->front>=SIZE)
return 1;
return 0;
}
void init(queue *q) //初始化队列,初始化时队头与队尾相同
{
q->element=(int*)malloc(SIZE*sizeof(int));
q->front=q->rear=0;
}
void push(queue *q,int e)
{
if(!isFull(q))
{
int pos=q->rear%SIZE;
q->element[pos]=e;
q->rear++;
}
}
int pop(queue *q)
{
int data=-1;
int pos=q->front%SIZE;
if(!isEmpty(q)&&q->element[pos]!=0)
{
data=q->element[pos];
q->element[pos]=0;
q->front++;
}
return data;
}
int _tmain(int argc, _TCHAR* argv[])
{
queue q;
init(&q);
cout<<"-------------------测试1-----------------------"<<endl;
push(&q,1);
push(&q,2);
cout<<pop(&q)<<endl;
push(&q,3);
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<"-------------------测试2-----------------------"<<endl;
push(&q,1);
push(&q,2);
push(&q,3);
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
push(&q,4);
push(&q,5);
push(&q,6);
push(&q,7);
push(&q,8);
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<"-------------------测试3-----------------------"<<endl;
push(&q,1);
push(&q,2);
push(&q,3);
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
cout<<pop(&q)<<endl;
return 0;
}