Hi I am working on assignment where we have to Insert integers into an IntSet in sorted order, I think I know what I am wanting to do in my head however implementing it into code has proved difficult, The main part I am having trouble with is having nodes point to NULL, for example if I insert 1 and then insert 2 my program crashes because I believe that 1 is still pointing to NULL, my code does work if I insert 1 and then -1 but if I insert 0 it again crashes, below is my code
void IntSet::insert( int entry )
// Modification member function
// PRE: (none)
// POST: If entry is not already in the IntSet, then the entry is added;
// otherwise, set is not changed
{
IntSetNode* newNode;
if ( find( entry ) )
{
return; // The element is already in the IntSet
}
if ( list == NULL )
{
// Construct a new node to hold this integer
newNode = new IntSetNode;
newNode->item = entry;
// Insert the new node into our list
newNode->next = list;
list = newNode;
// Increment the 'count' variable
count++;
}
if (list->item > entry)
{
newNode = new IntSetNode;
newNode->item = entry;
// Insert the new node into our list
newNode->next = list;
list = newNode;
count++;
}
//If entry is greater than previous node
if(list->item < entry)
{
//Construct new node
IntSetNode* cursor = list;
newNode = new IntSetNode;
//Insert new node into the list
cursor = cursor->next;
cursor->next = newNode;
//Increment count
count++;
}
}