循环队列(C语言版)

<pre name="code" class="cpp">#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);
int DeleteQueue(SeqQueue &Q,QueueElementType &x);
QueueElementType FrontQueue(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 = FrontQueue(q); 
    cout<<"队头元素为:"<<x<<endl; 
    x = BackQueue(q); 
    cout<<"队尾元素为:"<<x<<endl; 
    OutputQueue(q);
    cout<<"Len:"<<QueueLength(q)<<endl;
    EnterQueue(q,20);
    cout<<"入队元素20后,"; 
    OutputQueue(q);
    cout<<"进行一次出队操作!"<<endl; 
    DeleteQueue(q,x);
    cout<<"出队元素为:"<<x<<endl;
    OutputQueue(q);
    x = BackQueue(q);
    cout<<"队尾元素为:"<<x<<endl;
	x = FrontQueue(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;
}

int DeleteQueue(SeqQueue &Q,QueueElementType &x)
{
    if(IsEmpty(Q))
    {
        cout<<"当前队列为空,出队列失败!"<<endl;
        return -1;
    }
    else
    {
        x = Q.elem[Q.front];
        Q.front = (Q.front+1)%MAXSIZE;
        return 0;
    }

}

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];
}

QueueElementType FrontQueue(SeqQueue Q)
{
    return Q.elem[Q.front];
}

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


                
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值