//
// 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;
}