Set Class - Insert function

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}


1
2
3
4
5
6
Set::Set()
{
   Num = 0;
   Head = new (nothrow) Node;
   Head->Succ = NULL;
}


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
55
56
57
58
59
60
61
62
63
64
65
66
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

  public:

    // Return information about the set
    //
    bool is_empty() const { return Num == 0; }
    unsigned size() const { return Num; }

    // Initialize the set to empty
    //
    Set();

    // De-initialize the set
    //
    ~Set();

    // Initialize the set using an existing set
    //
    Set( const Set& );

    // Assign into the set from another set
    //
    Set& operator=( const Set& );

    // Test for presence of a specified item in the set
    //
    bool is_present( const EType& ) const;

    // Remove a specified item from the set, if possible
    //
    bool remove( EType& );

    // Insert a specified item into the set, if possible
    //
    bool insert( const EType& );

    // Display the contents of the set
    //
    void write( ostream& ) const;

    // Produce the union of two sets
    //
    friend Set operator+( const Set&, const Set& );

    // Produce the intersection of two sets
    //
    friend Set operator^( const Set&, const Set& );

    // Produce the difference of two sets
    //
    friend Set operator-( const Set&, const Set& );
};

#endif 


Tell me if anything else is needed for you to assist me...
You need to traverse your linked list to find the insertion point. Presently you are attempting to inserted at the head of the list.

A set is a collection that does not allow duplicates. Shouldn't you be traversing the list anyway to see if the element exists?

I'd imagine each node in the list to represent an element in the set, but your constructor creates an empty node. Are you sure you want to do that?
Topic archived. No new replies allowed.