zoukankan      html  css  js  c++  java
  • [C++] 习题 2.15 实现简单环形队列

    设计一个环形队列,用front和rear分别作为队头和队尾指针,另外用一个tag表示队列是空 ( 0 ) 还是不空 ( 1 ),这样就可以用front==rear作为队满的条件。要求设计队列的相关基本运算算法。

    前置技能

    环形队列

    队列中进出时需要大量前移后移操作,除了链式队列,使用环形队列挪动下标也是一个不错的选择。队列的数据类型定义参考书第45页。

    环形队列

    具体实现

    原理很简单,实现的时候要注意判断tag在数入队、出队时,是否要转换真假值。另外清除队列时只需要把头尾相对,队列标空。

    #include<iostream>
    
    template<class T>
    class queue{
    	private:
    		int maxsize;
    		int front;
    		int rear;
    		bool tag;
    		T *data;
    	public:
    		queue(int size){
    			maxsize = size;
    			front = 0;
    			rear = 0;
    			tag = false;
    			data = new T [size];
    		}
    		~queue(){
    			delete data;
    		}
    		void clear(){            //清除
    			rear = front;
    			tag = false;
    		}
    	    bool enqueue (T tmp){    //入队
    	    	if(full()){
    	    		return false;
    	    	}
    	    	else{
    		    	if(empty()){
                        tag = true;
    		    	}
    		    	data[rear] = tmp;
    		    	rear = (rear+1) % maxsize;
    		    	return true;
    	    	}
    	    }
    	    bool dequeue (T &tmp){   //出队
    	    	if(empty()){
    	    		return false;
    	    	}
    	    	else{
    		    	tmp = data[front];
    		    	front = (front+1) % maxsize;
    		    	if(front == rear){
    		    		tag = false;
    		    	}
    	    		return true;
    	    	}
    	    }
    	    bool getfront (T &tmp){
    	    	if(empty()){
    	    		return false;
    	    	}
    	    	else {
    	    		tmp = data[front];
    	    		return true;
    	    	}
    	    }
    		bool empty(){
    			if (rear == front && tag == false){
    				return true;
    			}
    			else{
    				return false;
    			}
    		}
    		bool full(){
    			if (rear == front && tag == true){
    				return true;
    			}
    			else{
    				return false;
    			}
    		}
    };
    
  • 相关阅读:
    oracle 存储过程 技巧
    任何用户密码都能以sysdba角色登入
    DBA操作常用命令
    事务 脏数据
    Axis2 WebService(配置、发布、调用)
    C#接口
    纯CSS3实现的一些酷炫效果
    C#运算符大全_各种运算符号的概述及作用
    mvc图片上传到服务器
    C# .NET 基本概念
  • 原文地址:https://www.cnblogs.com/winng/p/algorithm_circle_queue.html
Copyright © 2011-2022 走看看