Implementing an Insert method to create a sorted array

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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++;
   }
   
}


any help would be great, Thanks
You do not handle the equality case.

In the case where list->item < entry you do not insert properly.
You should do something like:
1
2
3
4
5
while( cursor->next && (cursor->next->item < entry) )
    cursor = cursor->next;

newNode->next = cursor->next;
cursor->next = newNode;
Thanks a lot, however when I insert a number say 1 and then insert 2 i get an array like

(1, - large number) and then when i inserted 3 it went
(1, - large number, - same large number)

is there something I need to do to the while loop?
Last edited on
Try removing line 4 of toums code.
you also forgot newNode->item = entry;
I guess that might help, thanks a lot guys it works now
Topic archived. No new replies allowed.