顺序结构
typedef struct{
int* data;
int front,rear;
int maxsize;
}Squeue,*Queue;
循环队列
顺序结构
typedef int ElemType; //ElemType的类型根据实际情况而定,这里假定为int
#define MAXSIZE 50 //定义元素的最大个数
/*循环队列的顺序存储结构*/
typedef struct{
ElemType data[MAXSIZE];
int front; //头指针
int rear; //尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;
(1)初始化
Queue init(int maxsize){
Queue Q=(Queue)malloc(sizeof(Squeue));
Q->data=(int*)malloc(sizeof(int));
Q->front=0;
Q->rear=0;
Q->maxsize=maxsize;
return Q;
}
(2)判队空
bool isempty(Queue Q){
if(Q->rear==Q->front){
return true;
}
else{
return false;
}
}
(3)求长度
/*返回Q的元素个数,也就是队列的当前长度*/
int QueueLength(SqQueue Q){
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
(4)入队
Queue Add(Queue Q,int e){
if(isempty(Q)){
printf("队列空");
return ERROR;
}
else{
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)%Q->maxsize;
return Q;
}
}
(5)出队
/*若队列不空,则删除Q中队头元素,用e返回其值*/
Status DeQueue(SqQueue *Q, ElemType *e){
if(isEmpty(Q)){
return REEOR; //队列空的判断
}
*e = Q->data[Q->front]; //将队头元素赋值给e
Q->front = (Q->front + 1) % MAXSIZE; //front指针向后移一位置,若到最后则转到数组头部
}
(6)删除节点
BTree Delete(Queue Q){
BTree front=Q->data[Q->front];
Q->front=(Q->front+1)%Q->maxsize;
return front;
}
链式结构
/*链式队列结点*/
typedef struct {
ElemType data;
struct LinkNode *next;
}LinkNode;
/*链式队列*/
typedef struct{
LinkNode *front, *rear; //队列的队头和队尾指针
}LinkQueue;
(1)初始化
void InitQueue(LinkQueue *Q){
Q->front = Q->rear = (LinkNode)malloc(sizeof(LinkNode)); //建立头结点
Q->front->next = NULL; //初始为空
}
(2)入队
Status EnQueue(LinkQueue *Q, ElemType e){
LinkNode s = (LinkNode)malloc(sizeof(LinkNode));
s->data = e;
s->next = NULL;
Q->rear->next = s; //把拥有元素e新结点s赋值给原队尾结点的后继
Q->rear = s; //把当前的s设置为新的队尾结点
return OK;
}
(3)出队
/*若队列不空,删除Q的队头元素,用e返回其值,并返回OK,否则返回ERROR*/
Status DeQueue(LinkQueue *Q, Elemtype *e){
LinkNode p;
if(Q->front == Q->rear){
return ERROR;
}
p = Q->front->next; //将欲删除的队头结点暂存给p
*e = p->data; //将欲删除的队头结点的值赋值给e
Q->front->next = p->next; //将原队头结点的后继赋值给头结点后继
//若删除的队头是队尾,则删除后将rear指向头结点
if(Q->rear == p){
Q->rear = Q->front;
}
free(p);
return OK;
}