/*
* stack1.h
*/
template <class T> class Stack
{
/*
* PURPOSE: Template for a stack of objects of any type T that has a
* copy constructor.
*
* NOTE: It is an error, and will produce unpredictable results, to
* try to pop or take the top of an empty stack.
*/
public:
Stack() : _top(NULL) { }
void push(T item) { _top = new StackNode(item, _top); }
T pop() { StackNode * removed = _top;
_top = _top -> _link;
T result = removed -> _item;
delete removed;
return result;
}
bool isEmpty() { return _top == NULL; }
T top() { return _top -> _item; }
private:
class StackNode
{
public:
StackNode(T item, StackNode * link)
: _item(item), _link(link) { }
T _item;
StackNode * _link;
} * _top;
};
/*
* Tester for stack1.h. It reads a line of characters from standard input,
* printing them out backwards, then forward again. Finally, it prints the
* individual ASCII codes of the characters. To do this, it uses two
* char stacks and one int stack.
*
*/
#include <std.h>
#include <iostream.h>
#include <bool.h>
#include "stack1.h"
main()
{
Stack < char > forward, backward;
Stack < int > ascii;
char c;
cout << "Input: ";
while ((c = cin.get()) != '\n')
backward.push(c);
cout << "Backward: ";
while (! backward.isEmpty())
{ char c = backward.pop();
cout << c;
forward.push(c);
ascii.push(c);
}
cout << endl;
cout << "Forward: ";
while (! forward.isEmpty())
{ char c = forward.pop();
cout << c;
}
cout << endl;
cout << "ASCII: ";
while (! ascii.isEmpty())
{ int i = ascii.pop();
cout << i << ' ';
}
cout << endl;
}
/*
* stack2.h
*/
template <class T> class Stack
{
/*
* PURPOSE: Template for a stack of objects of any type T that has a
* copy constructor.
*
* NOTE: It is an error, and will produce unpredictable results, to
* try to pop or take the top of an empty stack.
*/
public:
Stack();
void push(T item);
T pop();
bool isEmpty();
T top();
private:
class StackNode
{ public:
StackNode(T item, StackNode * link)
: _item(item), _link(link) { }
T _item;
StackNode * _link;
} * _top;
};
template < class T >
Stack<T>::Stack()
: _top(NULL)
{ }
template < class T >
void Stack<T>::push(T item)
{ _top = new Stack<T>::StackNode(item, _top); }
template < class T >
T Stack<T>::pop()
{ StackNode * removed = _top;
_top = _top -> _link;
T result = removed -> _item;
delete removed;
return result;
}
template < class T >
bool Stack<T>::isEmpty()
{ return _top == NULL; }
template < class T >
T Stack<T>::top()
{ return _top -> _item; }
Copyright ©1998 - Russell C. Bjork