I am working on a set class and I have successfully written an insert function, but I need the function to insert in an ordered fashion.

bool Set::insert( const EType & A )
{
   bool Flag = false;
   unsigned Position = 0;
   Node * Prev = Head;
   Node * Curr = Head->Succ;
   Node * Temp;

   Temp = new Node;
   if (Temp != NULL )
   {
      Temp->Item = A;
      Temp->Succ = Curr;
      Prev->Succ = Temp;
      Num++;
      Flag = true;
   }
   return Flag;
}
Set::Set()
{
   Num = 0;
   Head = new (nothrow) Node;
   Head->Succ = NULL;
}
class Set
{
  private:

    struct Node
    {
      EType Item;     // User data item
      Node * Succ;    // Link to the node's successor
    };

    unsigned Num;     // Number of user data items in the set
    Node * Head;      // Link to the head of the chain

Tell me if anything else is needed

Scan the set until you find a value higher or lower (depends on how you sort) then the current value, insert it there?

I tried doing that several separate times, but i cannot avoid a segmentation fault.

bool Set::insert( const EType & A )
{
   bool Flag = false;
   unsigned Position = 0;
   Node * Prev = Head;
   Node * Curr = Head->Succ;

   while ( (Curr->Item < A) and (Curr->Succ != NULL) )
   {
      Prev = Curr;
      Curr = Curr->Succ;
      cout << Curr->Item;
   }

   if ( (Curr->Item != A) or (Curr == NULL) )
   {
      Node * Temp;
      Temp = new Node;

      Temp->Item = A;
      Temp->Succ = Curr;
      Prev->Succ = Temp;
      Num++;
      Flag = true;
   }
   return Flag;
}
while ( (Curr->Item < A) and (Curr->Succ != NULL) )
   {
      Prev = Curr;
      Curr = Curr->Succ;
      cout << Curr->Item;
   }

That code sets Curr to the last item in the set that's smaller than A.
And then you compare the last item (curr->item) to A (to guarantee uniqueness) or NULL for the last item. And there's your problem I think, hehe.

What if Curr is NULL and you try to dereference Curr->item? Segfault. I hope that's the error.

So, correct code would be something like..

if(Curr == NULL){
//create new item, append it to the set
} else if (Curr->Item != A) {
//create new item, insert it between the two items.
}

I don't really understand the last post. I do understand the second part, but I'm confused about the while loop still.

While the current node's item is smaller than A and the current item isn't NULL (and thus we are at the end of the list), go to the next node.

This article has been dead for over six months. Start a new discussion instead.