数据结构---队列实现
2012-03-16 18:38
363 查看
栈是后进先出(先进后出),队列是先进先出(后进后出)。
我实现的是一个循环队列,当数组大小不够的时候,自动扩充大小。
废话不多说,看代码:
MyQueue.h
测试代码
我实现的是一个循环队列,当数组大小不够的时候,自动扩充大小。
废话不多说,看代码:
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"); }
相关文章推荐
- 数据结构--单链表实现队列1
- 【数据结构】栈以及两个栈实现一个队列
- 数据结构:循环队列(C语言实现)
- 数据结构-队列-链表实现
- 一步一步学数据结构之1--1(队列--单链表实现--含队头尾指针)
- 数据结构Java实现07----队列:顺序队列&顺序循环队列、链式队列、顺序优先队列
- 一步一步学数据结构之1--1(栈--两个队列实现)
- Python数据结构队列的实现
- 数据结构之链式队列go言语实现
- Python笔记——几种数据结构的实现:栈、队列及二叉树
- 算法导论第十章 基本数据结构实现(栈,队列,链表),课后题答案
- 数据结构Java实现07----队列:顺序队列&顺序循环队列、链式队列、顺序优先队列
- 数据结构:双向链表实现队列与循环链表
- 数据结构:循环队列(C语言实现)
- 简单数据结构的实现之循环队列
- 数据结构队列的java实现,包括线性和链式两种方式
- 数据结构(23)队列--单链表实现
- 使用JavaScript的数组实现数据结构中的队列与堆栈
- 数据结构之循环队列的实现
- 数据结构学习----链式队列(Java实现)