数据结构---队列实现

栈是后进先出(先进后出),队列是先进先出(后进后出)。

我实现的是一个循环队列,当数组大小不够的时候,自动扩充大小。


废话不多说,看代码:


MyQueue.h

#pragma once

template<typename T>
class MyQueue
{
private:
	int m_head;
	int m_tail;
	int m_arrSize;
	int m_count;
	T* m_QueueArray;
public:
	MyQueue();
	~MyQueue(void);

	bool isEmpty();
	bool pushBack(T item);
	T	 pop();//弹出最前一个,并且返回弹出的元素
	T	 top();
	int  getCount();
	
};

template<typename T>
MyQueue<T>::MyQueue(  )
{
	this->m_tail=-1;//尾元素索引地址
	this->m_head=-1;//首元素索引地址前一位
	this->m_count=0;
	this->m_arrSize=2;
	this->m_QueueArray=new T[m_arrSize];
}

template<typename T>
MyQueue<T>::~MyQueue( void )
{
	delete[] m_QueueArray;
}

template<typename T>
T MyQueue<T>::top()
{
	int first=(m_head+1)%m_arrSize;
	return m_QueueArray[first];
}

template<typename T>
bool MyQueue<T>::pushBack( T item )
{
	//当满了之后,需要申请更大的空间
	if (m_count==m_arrSize)
	{
		int newSize=m_arrSize*2;

		T* newArr=new T[newSize];

		int pos=0;
		T temp;
		while(!isEmpty())
		{
			newArr[pos]=pop();
			pos++;
		}

		m_count=pos;
		m_head=-1;
		m_arrSize=newSize;
		m_tail=m_count-1;

		delete[] m_QueueArray;

		this->m_QueueArray=newArr;
	}

	m_tail=(m_tail+1)%m_arrSize;

	m_QueueArray[m_tail]=item;
	
	m_count++;
	return true;
}

template<typename T>
bool MyQueue<T>::isEmpty()
{
	return m_count==0;
}


//弹出最前面一个元素
template<typename T>
T MyQueue<T>::pop()
{
	m_count--;
	int first=(m_head+1)%m_arrSize;
	T t=m_QueueArray[first];
	m_head=first;

	return t;
}

template<typename T>
int MyQueue<T>::getCount()
{
	return m_count;
}






测试代码

#include <iostream>
#include "MyQueue.h"
using namespace std;


struct Item
{
	int key;
	int count;
	
	Item(int _key,int _count)
	{
		key=_key;
		count=_count;
	}
	
	Item()
	{
		key=0;
		count=0;
	}
};

int main()
{
	MyQueue<Item> itemQueue=MyQueue<Item>();

	int i=30;
	while (i)
	{
		Item item=Item(i,i);
		itemQueue.pushBack(item);
		i--;
	}

	itemQueue.pop();
	itemQueue.pop();
	itemQueue.pushBack(Item(90,90));
	itemQueue.pushBack(Item(91,91));

	Item item;
	while(!itemQueue.isEmpty())
	{
		Item item=itemQueue.pop();

		cout<<item.key<<endl;

	}

	system("pause");
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值