#ifndef STACK_H
#define STACK_H
// Class Stack is a template for a bounded LIFO stack.
// Note that Stack only stores the pointers to its items (i.e. it is not "responsible" for its contents).
template<class T>
class Stack {
public:
// Default constructor
Stack(constint size = 10) : capacity(size), numberOfItems(0) {
if(size < 1) {
capacity = 10;
}
buffer = new T * [capacity];
}
// Destructor
~Stack() {
delete [] buffer;
}
// Checks if the stack contains any elements
bool empty() const {
return (numberOfItems < 1);
}
// Checks if the stack is full
bool full() const {
return (numberOfItems == capacity);
}
// Pushes a pointer to an element onto the stack, returns itself
Stack<T> & push(T * item) {
if(numberOfItems < capacity) {
buffer[numberOfItems++] = item;
}
return *this;
}
// Pops an elements off the stack, returns itself
Stack<T> & pop() {
if(!empty()) {
numberOfItems--;
}
return *this;
}
// Returns the pointer to the element at the top of the stack
T * peek() const {
if(!empty()) {
return buffer[numberOfItems-1];
}
return NULL;
}
// Output the contents of the stack to a stream
virtualvoid printOn(ostream & outstream) const {
outstream << "Contents:\n";
if(!empty()) {
for(int i=0; i < numberOfItems; i++) {
outstream << *(buffer[i]) << endl;
}
}
else {
outstream << "EMPTY\n";
}
return;
}
private:
T ** buffer;
int capacity, numberOfItems;
};
template<class T>
ostream & operator<<(ostream & ostr, const Stack<T> & aName) {
aName.printOn(ostr);
return ostr;
};
#endif // STACK_H
#ifndef LABELLEDSTACK_H
#define LABELLEDSTACK_H
#include "Stack.h"
// (Derived) Class LabelledStack is a template for a bounded LIFO stack with a label.
// Note that Stack only stores the pointers to its items (i.e. it is not "responsible" for its contents).
template <class T>
class LabelledStack : public Stack<T> {
public:
// Default constructor
LabelledStack(constint size, string newLabel) : Stack<T>(size){
this->label = new string(newLabel);
}
// Destructor
~LabelledStack() {
delete label;
}
// Output the contents of the stack to a stream
void printOn(ostream & outstream) const {
outstream << "Stack label: " << *label << endl;
Stack<T>::printOn(outstream);
return;
}
private:
string * label;
};
#endif // LABELLEDSTACK_H