Note that a stack is Last-in-first-out (LIFO). The last item pushed on the stack is the item that comes out when we look at the top. It is also the item removed when the stack is popped.
Code for a stack class might look like the following. First the class definition (in Stack,h):
#define ZERO 0;
const int MAXSIZE = 100;
typedef int stackData;
class Stack
{
public:
Stack ();
int getSize();
void push (stackData);
void pop ();
stackData getTop ();
bool isEmpty();
private:
stackData theList [MAXSIZE];
int size;
};
Of course a more flexible design would use a dynamic array (or a linked list) instead of a static array.
Here is the code for the functions of the class (in Stack.cpp):
#include "Stack.h"
Stack::Stack ()
{
size = 0;
}
int Stack::getSize ()
{
return size;
}
void Stack::push (stackData item)
{
if (size < MAXSIZE)
{
theList [size] = item;
size++;
}
}
void Stack::pop ()
{
if (size > 0)
size--;
}
stackData Stack::getTop ()
{
stackData returnVal = ZERO;
if (size > 0)
returnVal = theList [size - 1];
return returnVal;
}
bool Stack::isEmpty ()
{
return (size == 0);
}
The following code uses a stack to print a string in reverse. To make it work the first two lines in Stack.h must be changed to:
#define ZERO '\0' typedef char stackData;
Now for the program:
#include <iostream>
#include <string>
#include "Stack.h"
using namespace std;
int main ()
{
string aString = "my dog has fleas";
Stack theStack;
for (int n = 0; n < aString.size (); n++)
theStack.push (aString [n]);
while (!theStack.isEmpty ())
{
cout << theStack.getTop ();
theStack.pop ();
}
return 0;
}