• 顺序队列之C++实现


              下面介绍下用C++实现的顺序队列,在VC6下调试通过。

    1、文件组织形式

    2、sq.h顺序队列类的说明

    #ifndef _SQ_H_
    #define _SQ_H_
    
    typedef int dataType;
    #define maxSize 100
    
    class sq
    {
    public:
    	sq();
    	//~sq();
    	void push(dataType var);
    	void pop();
    	dataType front();
    	bool isEmpty();
    	bool isFull();
    
    private:
    	dataType queue[maxSize];
    	int head;
    	int tail;
    };
    
    #endif


    3、sq.cpp顺序队列类的定义

    #include <iostream>
    #include "sq.h"
    using namespace std;
    
    sq::sq()
    {
    	head = -1;   
    	tail = -1;
    }
    
    void sq::push(dataType var)
    {
    	queue[++tail] = var;
    
    	if(tail == 0) 
    	{
    		head = 0;
    	}
    }
    
    void sq::pop()
    {
    	++head;
    }
    
    dataType sq::front()
    {
    	return queue[head];
    }
    
    bool sq::isEmpty()
    {
    	bool flag = head > tail;     //当head和tail不为-1时
    
    	if(head == -1 && tail == -1) //当head=tail=-1时
    	{
    		flag = true;
    	}
    
    	if(flag)
    	{
    		head = tail = -1;
    	}
    
    	return flag;
    }
    
    bool sq::isFull()
    {
    	return tail == maxSize-1;
    }


    4、main.cpp

    #include <iostream>
    #include "sq.h"
    using namespace std;
    
    int main()
    {
    	sq exp;
    	int i = 0;
    
    	for(i=0;i<maxSize+10;++i)
    	{
    		if(!exp.isFull())
    		{
    			exp.push(i);
    		}
    	}
    	
    
    	for(i=0;i<maxSize+20;++i)
    	{
    		if(!exp.isEmpty())
    		{
    			cout<<exp.front()<<endl;
    			exp.pop();
    		}
    	}
    
    	if(exp.isEmpty())
    	{
    		cout<<"队列已空!"<<endl;
    	}
    
    	return 0;
    }
  • 相关阅读:
    CSU-ACM集训-模板-主席树
    Codeforces- Educational Codeforces Round 69
    Codeforces-Round#574 Div2
    CF-1183C Computer Game
    CSU-ACM2019暑假训练(2)
    CSU-ACM2019暑假集训(1)
    2019牛客网第二场-F题
    洛谷P1111 修复公路
    求强连通分量-korasaju算法
    并查集-路径优化+秩优化
  • 原文地址:https://www.cnblogs.com/james1207/p/3294033.html
Copyright © 2020-2023  润新知