1、队列
#include<iostream>
using namespace std;
template<class T>
class ArrayQueue
{
public:
ArrayQueue();
bool empty(){return listSize==0;};
int size(){return listSize;}
T& front();
T& back();
void pop();
void push(const T& theElement);
private:
int queueFront;
int listSize;
int arrayLength;
T* queue;
};
template<class T>
ArrayQueue<T>::ArrayQueue()
{
arrayLength=20;
listSize=0;
queueFront=-1;
queue=new T[arrayLength];
}
template<class T>
T& ArrayQueue<T>::front()
{
if(listSize!=0)
return queue[queueFront+1];
else
cout<<"queue is null!"<<endl;
}
template<class T>
T& ArrayQueue<T>::back()
{
if(listSize!=0)
return queue[queueFront+listSize];
else
cout<<"queue is null!"<<endl;
}
template<class T>
void ArrayQueue<T>::pop()
{
if(listSize!=0)
{
queue[queueFront+1].~T();
queueFront=(queueFront+1)%arrayLength;
listSize--;
}
else
cout<<"queue is null!"<<endl;
}
template<class T>
void ArrayQueue<T>::push(const T& theElement)
{
if(listSize==arrayLength)
{
T* temp=new T[arrayLength*2];
if(queueFront==0)
for(int i=0;i<listSize;i++)
copy(queue,queue+listSize,temp);
else
{
for(int i=queueFront;i<arrayLength;i++)
temp[i-queueFront]=queue[i];
for(int i=0;i<queueFront;i++)
temp[i+arrayLength-queueFront]=queue[i];
}
delete []queue;
queue=temp;
queueFront=0;
arrayLength*=2;
}
listSize++;
int queueBack=(queueFront+listSize)%arrayLength;
queue[queueBack]=theElement;
}
2、栈
template<class T>
class ArrayStack
{
public:
ArrayStack(int initialCapacity=20);
void push(const T&);
~ArrayStack()
{delete []stack;}
bool empty()const
{return stackTop==-1;}
int size()const
{return stackTop+1;}
T& top()
{
return stack[stackTop];
}
void pop()
{
stack[stackTop--].~T();
}
private:
T *stack;
int stackTop;
int arrayLength;
};
template<class T>
ArrayStack<T>::ArrayStack(int initialCapacity)
{
arrayLength=initialCapacity;
stackTop=-1;
stack=new T[arrayLength];
}
template<class T>
void ArrayStack<T>::push(const T& theElement)
{
if(stackTop==arrayLength-1)
{
T *temp=new T[arrayLength*2];
for(int i=0;i<arrayLength;i++)
temp[i]=stack[i];
delete []stack;
stack=temp;
arrayLength*=2;
}
stack[++stackTop]=theElement;
}