stack1.cpp
// stack1.cpp
//
// This is the first version of the Stack data structure, in C++
#include <iostream.h>
#include <assert.h>
#include <string.h> // For memmove()
class Stack
{
public:
Stack( int NewSize=0 );
~Stack();
int Push( int Value );
int Pop( int* Dest );
int IsFull() { return( Index==Size ); }
int IsEmpty() { return( Index==0 ); }
private:
int Size, Index, *Body;
enum GB { GrowBy=8 };
};
// Stack constructor - invoked automatically when object is constructed
Stack::Stack( int NewSize )
{
if( Size==0 )
{
Size=Index=0;
Body=0;
}
else
{
Body = new int[NewSize]; // Get memory from heap, like malloc() in C
assert( Body!=0 );
Index = 0;
Size = NewSize;
}
}
// Stack Destructor - Invoked automatically when object is destroyed
Stack::~Stack()
{
delete [] Body; // return memory to heap (like free(), in C)
}
// Stack::Push - Places a value on the stack object
int Stack::Push( int Value )
{
if( Index+1 >= Size )
{
int * Tmp;
Tmp = new int[Size+GrowBy];
if( Tmp==0 )
return( 0 );
Size += GrowBy;
memmove( Tmp, Body, Size*sizeof(int) );
delete [] Body;
Body = Tmp;
}
Body[Index++] = Value;
return(1);
}
// Stack::Pop - Removes value from the stack
int Stack::Pop( int* Dest )
{
if( Index )
{
*Dest = Body[--Index];
return(1);
}
return(0);
}
void main()
{
Stack X;
int V;
X.Push(1);
X.Push(2);
X.Push(3);
while( X.Pop(&V) == 1 )
cout << V << endl;
// Note: Destructor for X automatically called
}