循环队列的顺序存储
队列是只允许一端插入一端删除的数据结构,为“先进先出表”。
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int ElementType;
struct QNode {
ElementType *Data; /* 存储元素的数组 */
int Front, Rear; /* 队列的头、尾指针 */
int MaxSize; /* 队列最大容量 */
};
typedef struct QNode *Queue;
//创建空队列
Queue CreateQueue( int MaxSize )
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
Q->Front = Q->Rear = 0;
Q->MaxSize = MaxSize;
return Q;
}
//判队列满
bool IsFull( Queue Q )
{
return ((Q->Rear+1)%Q->MaxSize == Q->Front);
}
//队列的插入
bool AddQ( Queue Q, ElementType X )
{
if ( IsFull(Q) ) {
cout<<"队列满"<<endl;
return false;
}
else {
Q->Rear = (Q->Rear+1)%Q->MaxSize;
Q->Data[Q->Rear] = X;
return true;
}
}
//判队列空
bool IsEmpty( Queue Q )
{
return (Q->Front == Q->Rear);
}
//队列的删除
#define Error -1
ElementType DeleteQ( Queue Q )
{
if ( IsEmpty(Q) ) {
cout<<"队列空"<<endl;
return Error;
}
else {
Q->Front = (Q->Front+1)%Q->MaxSize;
return Q->Data[Q->Front];
}
}
//例子
int main()
{
int i,m,n;
Queue q = CreateQueue(100);
cin>>i;
while(i--){
cin>>n;
AddQ(q,n);
}
while(!(IsEmpty(q))){
m=DeleteQ(q);
cout<<m<<" ";
}
return 0;
}
链队列
#include<iostream>
#include<cstdlib>
using namespace std;
typedef int ElementType;
struct Node { /* 队列中的结点 */
ElementType Data;
struct Node *Next;
};
typedef struct Node *Position;
struct QNode { /*链队列结构*/
Position Front, Rear; /* 队列的头、尾指针 */
};
typedef struct QNode *Queue;
//创建空链队列
Queue CreateQueue()
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Front = Q->Rear = NULL;
return Q;
}
//判链队列空
bool IsEmpty( Queue Q )
{
return ( Q->Front == NULL);
}
//链队列的插入(不带头结点)
void AddQ(Queue Q,ElementType X)
{
Position TmpCell = (Position)malloc(sizeof(struct Node));
TmpCell->Data = X;
TmpCell->Next = NULL;
if( IsEmpty( Q ) ){
Q->Front = Q->Rear = TmpCell;
}else{
Q->Rear->Next = TmpCell;
Q->Rear = TmpCell;
}
}
//链队列的删除(不带头节点)
#define Error -1
ElementType DeleteQ( Queue Q )
{
Position FrontCell;
ElementType FrontElem;
if ( IsEmpty(Q) ) {
cout<<"队列空"<<endl;
return Error;
}
else {
FrontCell = Q->Front;
if ( Q->Front == Q->Rear ) /* 若队列只有一个元素 */
Q->Front = Q->Rear = NULL; /* 删除后队列置为空 */
else
Q->Front = FrontCell->Next;
FrontElem = FrontCell->Data;
free( FrontCell ); /* 释放被删除结点空间 */
return FrontElem;
}
}
int main()
{
int i,m,n;
Queue q = CreateQueue();
cin>>i;
while(i--){
cin>>n;
AddQ(q,n);
}
while(!(IsEmpty(q))){
m=DeleteQ(q);
cout<<m<<" ";
}
return 0;
}