Here is the code:
#include "DynIntStack.h"
DynIntStack::DynIntStack(void)
{
}
DynIntStack::~DynIntStack(void)
{
}
bool DynIntStack::IsEmpty()
{
return head;
}
void DynIntStack::Push(int v)
{
Element e = Element(v, head);
head = &e;
}
int DynIntStack::Pop()
{
if(head)
{
int r = head->v;
head = head->next;
return r;
}
}
int DynIntStack::Top()
{
if(head)
return head->v;
}
string DynIntStack::Print()
{
stringstream ss;
ss << "IntStack {";
Element *k = head;
while (k)
{
ss << k->v << ", ";
k = k->next;
}
ss << "}";
return ss.str();
}
The "head" pointer seems to lose its value every time I call push. Why? Often times the head element will contain a pointer to ITSELF, which should not be possible with this code...