链队列:
/*
链队列
*/
#include <malloc.h>
#include <iostream>
typedef int type;
typedef bool status;
typedef struct tyust
{
type data;
struct tyust *next;
}*node;
struct queue
{
node front,rear;
};
/*
队列初始化
*/
void queue_init(queue &q)
{
q.front=q.rear=(node)malloc(sizeof(tyust));
if(!q.front)cout<<"ERROR!!";
q.front->next=NULL;
}
/*
插入元素
*/
void Enqueue(queue &q,type e)
{
node p;//建立新节点
p=(node)malloc(sizeof(tyust));
p->data=e;
p->next=NULL;
q.rear->next=p;
q.rear=p;
}
//判断队列是否空
status isempty(queue q)
{
if(q.front->next==NULL)
return true;
else return false;
}
//销毁队列
void destroy(queue &q)
{
while(q.front)
{
q.front->next=q.rear;
free(q.front);
q.front=q.rear;
}
}
//清空队列
void clear(queue &q)
{
destroy(q);
queue_init(q);
}
//删除元素
status Dequeue(queue &q,type &e)//获得删除的元素
{
node p;
if(isempty(q)==true)return false;
else
{
//删除头元素
//头节点不存放数据
p=q.front->next;//队头
e=p->data;
q.front->next=p->next;
if(q.rear==p)
q.rear=q.front;
free(p);
return true;
}
}
//返回队列头元素
status getqueue(queue q,type &e)
{
node p;
if(q.front=q.rear)return false;//空队列
p=q.front->next;
e=p->data;
return true;
}
顺序循环队列:
/*
顺序循环队列
*/
#include <malloc.h>
#include <iostream>
typedef int type;
typedef bool status;
#define MAX_SIZE 10
struct queue
{
type *base;
int front;
int rear;
};
//初始化
void init(queue &q)
{
q.base=(type*)malloc(MAX_SIZE*sizeof(type));
if(!q.base)cout<<"error";
q.front=q.rear=0;
}
// 插入元素
void enqueue(queue &q,type e)
{
if((q.rear+1)%MAX_SIZE==q.front)
cout<<"队列已满!";
q.base[q.rear]=e;
q.rear=(q.rear+1)%MAX_SIZE;
}
//删除元素
status del_queue(queue &q,type &e)
{
if(q.front==q.rear)//空
return false;
e=q.base[q.front];
q.front=(q.front+1)%MAX_SIZE;
return true;
}
//返回队列元素个数
int length(queue q)
{
return (q.rear-q.front+MAX_SIZE)%MAX_SIZE;//+MAX_SIZE是防止出现q.rear<q.front情况
}