由于非循环队列的操作非常简单,并且在出队后会产生很多无法利用的空间,所以在此处不使用非循环队列。一下的介绍均是循环对立。
二、链表实现的队列 (不带头节点)一下代码均是经过测试的,可以直接上机运行。
#include#include using namespace std; //用顺序表表实现循环队列 #define MaxSize 100 typedef struct{ int data[MaxSize]; int front,rear; //队头指针和队尾指针 int size; //用来记录队列中元素的个数,在队列的判空和判满里面使用, //节约一个存储单元 }SqQueue; //队列的初始化 void InitQueue(SqQueue &Q){ Q.front = 0; Q.rear = 0; Q.size = 0; } //判空,容易出错 bool IsEmpty(SqQueue Q){ return ((Q.rear == Q.front) && Q.size ==0); } //判满 bool IsFull(SqQueue Q){ return ((Q.rear == Q.front) && Q.size == MaxSize); } //入队 bool EnQueue(SqQueue &Q, int x){ if(IsFull(Q)) return false; Q.data[Q.rear] = x; Q.rear = (Q.rear + 1)%MaxSize; Q.size++; return true; } //出队 bool DeQueue(SqQueue &Q,int &y){ if(IsEmpty(Q)) return false; y = Q.data[Q.front]; Q.front = (Q.front + 1)% MaxSize; return true; } int main(){ //测试 SqQueue Q; int x,y; InitQueue(Q); //cout<
#include#include #include using namespace std; //用链表实现的队列(不带头节点) typedef struct linkNode{ int data; struct linkNode *next; }linkNode; typedef struct{ linkNode *front,*rear; }linkQueue; //初始化 void InitQueue(linkQueue &Q){ Q.front = NULL; Q.rear = NULL; } //判断队列是否为空 bool IsEmpty(linkQueue Q){ if(Q.front == NULL) return true; else return false; } //入队操作,尾节点插入 bool EnQueue(linkQueue &Q,int x){ linkNode *p = (linkNode*)malloc(sizeof(linkNode)); //if(p == NULL) //return false; p->data = x; p->next = NULL; if(Q.front == NULL){ Q.front = p; Q.rear = p; } else { Q.rear->next = p; Q.rear = p; } return true; } //出队操作,在头节点删除 bool DeQueue(linkQueue &Q,int &x){ //判断是否是空的队列 if(IsEmpty(Q)) return false; linkNode *p = Q.front; x = p->data; //如果删除的是最后一个元素 if(Q.front == Q.rear){ Q.front = NULL; Q.rear = NULL; } else{ Q.front = p->next; } //free(p); //C++s实现的不需要再free了,会出错,c语言可以添加这一行 return true; } int main(){ linkQueue Q; int x; InitQueue(Q); for(int i = 0; i < 10; i++){ x = random()%100; EnQueue(Q,x); } for(int i = 0; i < 10; i++){ DeQueue(Q,x); printf("%d ",x); } return 0; }



