zoukankan      html  css  js  c++  java
  • 循环队列

    问题:主要是队列为空和满的条件.

             为空:cqueue->front==cqueue->rear  为满(cqueue->rear+1)==cqueue->front

    代码:

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    #define MAXSIZE 20
    typedef struct CQueue
    {
    	int front;
    	int rear;
    	int data[MAXSIZE];
    }*CirQueue;
    
    void initCQueue(CirQueue &cqueue)
    {
    	cqueue=(CirQueue)malloc(sizeof(struct CQueue));
    	if(!cqueue)
    	{
    		cout<<"allocate fail"<<endl;
    		exit(-1);
    	}
    	else
    	{
    		cqueue->front=cqueue->rear=0;
    	}
    }
    
    void enCQueue(CirQueue cqueue,int elem)
    {
    	if((cqueue->rear+1)%MAXSIZE==cqueue->front)
    	{
    		cout<<"循环队列已满"<<endl;
    		exit(0);
    	}
    	else
    	{
    		cqueue->data[cqueue->rear%MAXSIZE]=elem;
    		cqueue->rear++;
    	}
    }
    
    int deCQueue(CirQueue cqueue)
    {
    	int elem;
    	if(cqueue->front==cqueue->rear)
    	{
    		cout<<"队列已空"<<endl;
    		exit(0);
    	}
    	else
    	{
    		elem=cqueue->data[cqueue->front%MAXSIZE];
    		cqueue->front++;
    	}
    	return elem;
    }
    
    int main()
    {
    	CirQueue cqueue;
    	int arr[]={1,2,3,4,5,6,7,9,0};
    
    	initCQueue(cqueue);
    
    	cout<<"循环队列入队:1 2 3 4 5 6 7 9 0:"<<endl;  
    	for(int i=0;i<9;i++)
    	{
    		enCQueue(cqueue,arr[i]);
    	}
    
    	cout<<"循环队列出队:"<<endl;
    	while(cqueue->front!=cqueue->rear)
    	{
    	    cout<<deCQueue(cqueue)<<"  ";
    	}
    	cout<<endl;
    	return 0;
    }
    

    运行结果:

  • 相关阅读:
    nginx配置文件详解
    centos 小知识
    nginx 常见问题
    centos7.5 安装nginx
    tomact 配置远程登录
    Centos7 离线安装 mariaDB
    Crontab详细用法-定时任务详解
    新项目push/pull到github
    GIT的基本操作
    hive的安装
  • 原文地址:https://www.cnblogs.com/xshang/p/3033975.html
Copyright © 2011-2022 走看看