I’m learning programming and I’ve wanted to make some basic data structures. I tried to search over here but I didn’t find any solution (ok, neither similiar problem). Here is the code:
#include <iostream>
using namespace std;
class Data
{
public:
Data(int value):thatValue(value) {}
~Data(){}
void Show() {cout << thatValue << "\n";}
private:
int thatValue;
};
class Node
{
public:
Node(Data * pData, Node * Next);
~Node() {delete thatData; thatData=0; delete thatNext; thatNext=0;}
void ShowData() {thatData->Show();}
void ShowNext() {if(thatNext != 0) { thatNext->ShowData(); thatNext->ShowNext();}}
private:
Data * thatData;
Node * thatNext;
};
Node::Node(Data * pData, Node * Next)
{
thatData = pData;
thatNext = Next;
}
class LinkedList
{
public:
LinkedList(int size);
~LinkedList() {delete thatNext; thatNext=0; delete thatData; thatData=0;}
void Insert(Data * newData);
void PrintAll();
private:
Node * thatNext;
Data * thatData;
};
LinkedList::LinkedList(int size)
{
thatNext = 0;
for (int i = 0; i <= size; i++)
{
thatData = new Data(i);
Insert(thatData);
}
}
void LinkedList::Insert(Data * newData)
{
Node * pNode = new Node(newData, thatNext);
thatNext = pNode;
}
void LinkedList::PrintAll()
{
thatNext->ShowData();
thatNext->ShowNext();
}
int main ()
{
LinkedList * LS = new LinkedList(100000);
LS->PrintAll();
delete LS;
return 0;
}
So the problem is, that when the linked list is small enough (<50000 items), then the program execute as i expected. But when it has more items, it crashes, while it is executing function LinkedList::PrintAll().
I’m sorry if the problem is something stupid or obvious, or if the impletation is completely wrong. But I cannot see the problem.
You get a stack overflow. Why do you do it recursively? Just make a simple loop.
or something similar…