/**
* @brief Stack and Queue
* @author An
* @data 2013.5.21
**/
#ifndef STACKANDQUEUE_H
#define STACKANDQUEUE_H
#define stackSize 50
#define queueSize 50
#include <iostream>
using namespace std;
template <class Type>
class Stack
{
public:
Stack(): index( -1 ) { }
bool empty()
{
if ( index == -1)
return true;
else
return false;
}
int maxSize()
{
return stackSize;
}
int size()
{
return index + 1;
}
Type top()
{
if ( empty() )
{
cout << "ERROR: The Stack is empty! " << endl;
return -1;
}
return array[ index ];
}
void push( Type newElem )
{
if ( index >= stackSize - 1 )
{
cout << "The stack is full!" << endl;
}
else
{
++index;
array[ index ] = newElem;
}
}
void pop()
{
if ( index == -1 )
{
cout << "The stack is empty!" << endl;
}
else
{
--index;
}
}
private:
Type array[ stackSize ];
int index;
};
template <class Type>
class Queue
{
public:
Queue(): head(0), tail(0) {}
bool empty()
{
if ( head == tail )
return true;
else
return false;
}
int size()
{
if ( tail >= head )
return tail - head;
else
return tail - head + queueSize;
}
int maxSize()
{
return queueSize;
}
Type front()
{
if ( empty() )
{
cout << "The queue is empty!" << endl;
return -1;
}
else
{
return array[ head ];
}
}
Type back()
{
if ( empty() )
{
cout << "The queue is empty!" << endl;
return -1;
}
if ( tail > 0 )
return array[ tail - 1 ];
else
return array[ queueSize ];
}
void EnQueue( Type newElem )
{
if ( (tail + 1) % queueSize == head )
{
cout << "The queue is full!" << endl;
}
else
{
array[ tail ] = newElem;
if ( tail == queueSize - 1 )
tail = 0;
else
++tail;
}
}
Type DeQueue()
{
if ( empty() )
{
cout << "The queue is empty!" << endl;
return -1;
}
Type tmp = array[ head ];
if ( head == queueSize - 1 )
head = 0;
else
++head;
return tmp;
}
private:
Type array[ queueSize ];
int head;
int tail;
};
#endif
#include "StackAndQueue.h"
#include <iostream>
using namespace std;
int main()
{
Stack<int> stk;
Queue<int> que;
for ( int i = 0; i <= 9; ++i )
{
stk.push( i );
}
for ( int i = 0; i <= 9; ++i )
{
que.EnQueue( stk.top() );
cout << que.back() << " ";
stk.pop();
}
cout << endl;
for ( int i = 0; i <= 9; ++i )
{
cout << que.DeQueue() << " ";
}
cout << endl;
return 0;
}