顺序队列
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
//顺序队列
typedef struct{
int data[MAX];
int front,rear;
}SqQueue;
void initQueue(SqQueue &Q){
Q.front=Q.rear=0;
}
bool isEmpty(SqQueue &Q){
return Q.front==Q.rear;
}
bool isFull(SqQueue &Q){
return ((Q.rear+1)%MAX)==Q.front;
}
void enQueue(SqQueue &Q,int e)
{
if(isFull(Q))
printf("queue is full:\n");
Q.data[Q.rear]=e;
Q.rear=(Q.rear+1)%MAX;
}
int deQueue(SqQueue &Q)
{
if(isEmpty(Q))
printf("queue is empty:\n");
int e;
e=Q.data[Q.front];
Q.front=(Q.front+1)%MAX;
return e;
}
void print(SqQueue &Q){
int i;
printf("Print the queue:\n");
for(i=Q.front;i%MAX<Q.rear;i++)
printf("%3d",Q.data[i]);
printf("\n");
}
void main(){
SqQueue q;
int e;
initQueue(q);
enQueue(q,1);
enQueue(q,3);
enQueue(q,5);
print(q);
e=deQueue(q);
printf("dequeue is %3d\n",e);
print(q);
}
链式队列
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct LinkNode{
ElemType data;
LinkNode *next;
}LinkNode;
typedef struct {
LinkNode *front,*rear;
}LinkQueue;
void initQueue(LinkQueue &Q){
Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode));
Q.front->next=NULL;
}
bool isEmpty(LinkQueue Q){
if(Q.front==Q.rear)
return true;
else return false;
}
void enQueue(LinkQueue &Q,ElemType x){
LinkNode *s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=x;s->next=NULL;
Q.rear->next=s;
Q.rear=s;
}
/*从队列中删除一个元素*/
int delQueue(LinkQueue &Q)
{
int temp;
if(Q.front==Q.rear) return false;
LinkNode *p=Q.front->next;
temp=p->data;
Q.front->next=p->next;
if(Q.rear==p){
Q.rear=Q.front;
}
free(p);
return temp; /*返回被删除的队首元素值*/
}
void print(LinkQueue &Q){
LinkNode *top=Q.front->next;
while(top){
printf("%3d",top->data);
top=top->next;
}
}
void main(){
LinkQueue q;
int a[8]={3,8,5,17,9,30,15,22};
int i;
initQueue(q);
for(i=0;i<8;i++)
{
enQueue(q,a[i]);
}
print(q);
printf("delnode is %d\n",delQueue(q));
printf("delnode is %d\n",delQueue(q));
}