循环队列(C语言版)
#include
using namespace std;
#define MAXSIZE 50
typedef int QueueElementType;
typedef struct
{
QueueElementType elem[MAXSIZE];
int front; //指向当前队头元素
int rear; //指向队尾元素的下一个位置
}SeqQueue;
void InitQueue(SeqQueue &Q);
void InputQueue(SeqQueue &Q);
bool EnterQueue(SeqQueue &Q,QueueElementType x);
QueueElementType DeleteQueue(SeqQueue &Q);
QueueElementType BackQueue(SeqQueue Q);//返回队尾元素
bool IsFull(SeqQueue Q);
bool IsEmpty(SeqQueue Q);
void OutputQueue(SeqQueue Q);
int QueueLength(SeqQueue Q);
int main()
{
int x;
SeqQueue q;
InitQueue(q);
InputQueue(q);
x = BackQueue(q);
cout<
OutputQueue(q);
cout<
EnterQueue(q,20);
cout<
OutputQueue(q);
x = DeleteQueue(q);
cout<
OutputQueue(q);
x = BackQueue(q);
cout<
return 0;
}
void InitQueue(SeqQueue &Q)
{
Q.front = Q.rear = 0;
}
void InputQueue(SeqQueue &Q)
{
cout<
int m;
cin>>m;
while(m!=-1)
{
if(IsFull(Q))
cout<
else
{
EnterQueue(Q,m);
cin>>m;
}
}
}
bool EnterQueue(SeqQueue &Q,QueueElementType x)
{
if((Q.rear+1)%MAXSIZE == Q.front)
return false;
Q.elem[Q.rear] = x;
Q.rear = (Q.rear+1)%MAXSIZE;
return true;
}
QueueElementType DeleteQueue(SeqQueue &Q)
{
if(IsEmpty(Q))
{
cout<
return -1;
}
else
{
int temp = Q.elem[Q.front];
Q.front = (Q.front+1)%MAXSIZE;
return temp;
}
}
bool IsFull(SeqQueue Q)
{
return (Q.rear+1)%MAXSIZE == Q.front;
}
bool IsEmpty(SeqQueue Q)
{
return Q.front == Q.rear;
}
void OutputQueue(SeqQueue Q)
{
if(IsEmpty(Q))
cout<
int temp = Q.front;
cout<
while(temp!=Q.rear)
{
cout<
temp = (temp+1)%MAXSIZE;
}
cout<
}
QueueElementType BackQueue(SeqQueue Q)
{
return Q.elem[(Q.rear-1)%MAXSIZE];
}
int QueueLength(SeqQueue Q)
{
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}