您的位置:首页 > 编程语言 > C语言/C++

队列(数组形式)实现_c++

2014-04-16 20:56 453 查看
template<class T> class Queue{
	friend ostream& operator<< <T> (ostream&, const Queue<T>&);
public:
	Queue(int maxcount = 10):head(0),tail(0), count(maxcount)
	{
		data = new T[count]();
	}

	Queue(const Queue& rhs):head(rhs.head), tail(rhs.tail), count(rhs.count)
	{
		data = new T[count]();

		memcpy(data, rhs.data, sizeof(T)*count);
	}

	Queue& operator=(const Queue& rhs)
	{
		if (this == &rhs)
		{
			return *this;
		}

		head = rhs.head;
		tail = rhs.tail;
		count = rhs.count;

		delete []data;

		data = new T[count]();
		memcpy(data, rhs.data, sizeof(T)*count);

		return *this;
	}

	~Queue()
	{
		delete []data;
	}

	T& Front() const;
	void Push(const T&);
	void Pop();
	size_t Size() const;
	inline bool Empty() const;
	inline bool Full() const;
private:
	int head;
	int tail;
	int count;
	T* data;
};

template<class T> T& Queue<T>::Front() const
{
	if (Empty())
	{
		exit(1);
	}
	return data[head];
}

template<class T> void Queue<T>::Push(const T& val)
{
	if (!Full())
	{
		data[tail] = val;
		tail = (tail+1)%count;
	}
}

template<class T> void Queue<T>::Pop()
{
	if (!Empty())
	{
		head = (head+1)%count;
	}
}

template<class T> size_t Queue<T>::Size() const
{
	return (tail-head+count)%count;
}

template<class T> bool Queue<T>::Empty() const
{
	return head == tail;
}

template<class T> bool Queue<T>::Full() const
{
	return (tail+1)%count == head;
}

template<class T> ostream& operator<<(ostream& os, const Queue<T>& q)
{
	if (!q.Empty())
	{
		for (int i = q.head; i != q.tail; i = (i+1)%q.count)
		{
			os<<q.data[i]<<' ';
		}
	}

	return os;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: