您的位置:首页 > 理论基础 > 数据结构算法

数据结构---队列实现

2012-03-16 18:38 363 查看
栈是后进先出(先进后出),队列是先进先出(后进后出)。

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

废话不多说,看代码:

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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: