循环队列(C语言版)

#include <iostream>
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<<"队尾元素为:"<<x<<endl; 
    OutputQueue(q);
    cout<<"Len:"<<QueueLength(q)<<endl;
    EnterQueue(q,20);
    cout<<"入队元素20后,"; 
    OutputQueue(q);
    x = DeleteQueue(q);
    cout<<"出队元素为:"<<x<<endl;
    OutputQueue(q);
    x = BackQueue(q);
    cout<<"队尾元素为:"<<x<<endl; 
	return 0;
}

void InitQueue(SeqQueue &Q)
{
    Q.front = Q.rear = 0;
}

void InputQueue(SeqQueue &Q)
{
    cout<<"请输入一组元素,以-1结束:";
    int m;
    cin>>m;
    while(m!=-1)
    {
        if(IsFull(Q))
            cout<<"当前队列已满,无法插入"<<endl;
        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<<"当前队列为空,出队列失败!"<<endl;
        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<<"当前队列为空!"<<endl;
    int temp = Q.front;
    cout<<"Out:";
    while(temp!=Q.rear)
    {
        cout<<Q.elem[temp]<<" ";
        temp = (temp+1)%MAXSIZE;
    }
    cout<<endl;
}

QueueElementType BackQueue(SeqQueue Q)
{
    return Q.elem[(Q.rear-1)%MAXSIZE];
}

int  QueueLength(SeqQueue Q)
{
    return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}


技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。