• 用数组实现队列(C++)


    #include <iostream>
    
    using namespace std;
    
    template<typename T, int size = 0>
    class Queue
    {
    public:
    	Queue();
    
    	bool isEmpty() const;
    	bool isFull()const;
    
    	void enQueue(const T&);
    	T deQueue();
    
    	void traverse()const;
    private:
    	T storge[size];
    	int first;
    	int last;
    };
    
    template<typename T, int size>
    Queue<T, size>::Queue()
    {
    	first = last = -1;
    }
    
    template<typename T, int size>
    bool Queue<T, size>::isEmpty()const
    {
    	//如果为空,first必然为-1,因为在deQueue()出栈函数中已经处理
    	return first == -1;
    }
    
    template<typename T, int size>
    bool Queue<T, size>::isFull()const
    {
    	//两种情况,第一种是正常的满,第二种是存在出队时的满
    	return first == 0 && last == size - 1 || last == first - 1;
    }
    
    
    template<typename T, int size>
    void Queue<T, size>::enQueue(const T& elem)
    {
    	if (!isFull())
    	{
    		//last为-1或指向最后一个元素的位置时
    		if (last == -1 || last == size - 1)
    		{
    			storge[0] = elem;
    			last = 0;
    			//若队列为空,还需将first赋为0
    			if (first == -1)
    			{
    				first = 0;
    			}
    		}
    		else
    		{
    			storge[++last] = elem;
    		}
    	}
    	else
    	{
    		cout << "Queue full." << endl;
    		exit(1);
    	}
    }
    
    template<typename T, int size>
    T Queue<T, size>::deQueue()
    {
    	if (isEmpty())
    	{
    		cout << "Queue empty." << endl;
    		exit(1);
    	}
    	T temp;
    	temp = storge[first];
    	//队列中只有一个元素时
    	if (first == last)
    	{
    		//这样,判断是否为空时只需判定first是否为-1
    		first = last = -1;
    	}
    	else if (first == size - 1)
    	{
    		//回到第一个元素位置
    		first = 0;
    	}
    	else
    	{
    		++first;
    	}
    	return temp;
    }
    
    template<typename T, int size>
    void Queue<T, size>::traverse()const
    {
    	for (auto i = first; i <= last; ++i)
    	{
    		cout << storge[i] << " ";
    	}
    	cout << endl;
    }
    
    
    int main()
    {
    	Queue<int, 3> queue;
    
    	queue.enQueue(10);
    	queue.enQueue(10);
    	queue.enQueue(10);
    
    	cout << queue.isFull() << endl;
    
    	queue.traverse();
    	queue.deQueue();
    	queue.traverse();
    	queue.deQueue();
    	cout << queue.isEmpty() << endl;
    	queue.deQueue();
    	cout << queue.isEmpty() << endl;
    	system("pause");
    	return 0;
    }
    

    运行测试:

    参考:C++实现队列--数组实现和链表实现

    感谢阅读,如有问题,请批评指正,谢谢。
  • 相关阅读:
    SQL Server控制语句
    MATLAB中取整函数(fix, floor, ceil, round)的使用
    MATLAB程序设计
    Thinking In Java<<Java编程思想>>
    Boost::bimap
    MySQL学习随笔1
    Boost 1_42_0在windows下的编译及其设置
    MySQL执行mysql脚本及其脚本编写
    Pygame介绍
    Erlang
  • 原文地址:https://www.cnblogs.com/clwsec/p/11564177.html
Copyright © 2020-2023  润新知