//
// main.cpp
// Data Structure TRY1
//
// Created by zr9558 on 6/7/13.
// Copyright (c) 2013 zr9558. All rights reserved.
//
// Data Structure C++, Weiss, P.104 Section 3.7 The Queue ADT
// make use of array to construct the class queue (FIFO)
/*
http://www.cplusplus.com/reference/queue/queue/
member functions:
empty Test whether container is empty (public member function)
size Return size (public member function)
front Access next element (public member function)
back Access last element (public member function)
push Insert element (public member function)
pop Delete next element (public member function)
*/
#include<iostream>
using namespace std;
template<typename Comparable>
class Queue
{
public:
Queue(){ theSize=0; theCapacity=10; Array= new Comparable[theCapacity];}
Queue(const Queue &rhs) { operator=(rhs);}
const Queue &operator=( const Queue &rhs)
{
if( this!=&rhs)
{
theSize=rhs.theSize;
theCapacity=rhs.theCapacity;
Array=new Comparable[theCapacity];
for( int i=0; i!=theSize; ++i)
Array[i]=rhs.Array[(rhs.front+i)%theCapacity];
front=0; back=theSize-1;
}
return *this;
}
~Queue() { delete []Array;}
bool Empty() const { return theSize==0;}
int Size() { return theSize;}
Comparable Front() { return Array[front];}
Comparable Back() { return Array[back];}
void Push( const Comparable &x)
{
if( theSize==theCapacity) reserve(2*theCapacity+1);
if( theSize==0)
{
front=back=0;
Array[0]=x;
++theSize;
}
else
{
back=(back+1)%theCapacity;
Array[back]=x;
++theSize;
}
}
void Pop()
{
front=(front+1)%theCapacity;
--theSize;
}
private:
Comparable * Array;
int theSize;
int theCapacity;
int front, back;
void reserve( int newCapacity)
{
if( newCapacity<theSize) return;
Comparable *oldArray=Array;
Array=new Comparable[newCapacity];
for( int i=0; i<theSize; ++i)
Array[i]=oldArray[(front+i)%theSize];
theCapacity=newCapacity;
front=0; back=theSize-1;
delete []oldArray;
}
};
int main()
{
Queue<int> Q;
for( int i=0; i<20; ++i)
{
Q.Push(i);
}
Queue<int> Q2(Q);
cout<<Q.Size()<<endl;
while( !Q.Empty())
{
cout<<Q.Front()<<" "<<Q.Back()<<endl;
Q.Pop();
}
cout<<endl;
cout<<Q.Size()<<endl;
cout<<Q2.Front()<<" "<<Q2.Back()<<endl;
cout<<Q2.Size()<<endl;
return 0;
}
队列ADT的C++实现:理解FIFO与队列操作
本文深入探讨了使用C++实现队列ADT(抽象数据类型)的方法,特别关注了FIFO(先进先出)原则。通过模板类Queue的构建,详细介绍了如何利用数组构造队列,并阐述了关键成员函数如empty、size、front、back、push和pop的使用。最后,通过实例展示了队列的操作,包括初始化、添加元素、删除元素和访问队首队尾元素的过程。
1102

被折叠的 条评论
为什么被折叠?



