I made own stack based on single linked list, and it works fine, but when I took a look at the memory usage... A console application using a stack containing 100k integers took 6.5 MB. It's terrible, because 4 byte * 100k = 0.38 MB. I allocate memory for every 'Unit' struct, which one contains a pointer to the next, but I don't think it would take a lot of memory. What the cause the problem?
template <typename T>
class Stack
{
struct Unit
{
Unit *prev;
T value;
Unit(T value);
};
public:
Stack();
void Push(T value);
int Count();
T Top();
T Pop();
~Stack();
private:
unsigned int count;
Unit *top;
};
template<typename T>
Stack<T>::Unit::Unit(T value)
{
this->value = value;
prev = nullptr;
}
template<typename T>
Stack<T>::Stack()
{
top = nullptr;
count = 0;
}
template<typename T>
void Stack<T>::Push(T value)
{
if (top == nullptr)
{
top = new Unit(value);
}
else
{
Unit *tmp = new Unit(value);
tmp->prev = top;
top = tmp;
}
count++;
}
template<typename T>
T Stack<T>::Pop()
{
T value = top->value;
Unit *tmp = top->prev;
delete top;
top = tmp;
count--;
return value;
}
template<typename T>
Stack<T>::~Stack()
{
Unit *curr = top;
if (!curr)
{
return;
}
while (curr)
{
Unit* tmp = curr->prev;
delete curr;
curr = tmp;
}
}