hello
hello

Reputation: 1228

Inserting object in ascending order in Linked List

What I'm trying to do is insert objects into a linked list in ascending order using the first parameter in the class constructor, char*. The code I have presently does not show any error, but the order isn't right.

So far, I have this piece of code below

void list::insert(Obj* NObj)
{
    if (head == NULL)
        head = NObj;
    else if (strcmp(NObj->name, head->name) < 0 ))
    {
        NObj->next = head;
        head = NObj;
    }
    else
    {
        Obj * t1 = head;
        Obj * t2 = t1->next;
        while ((t2 != NULL) && strcmp(NObj->name, head->name) < 0 )
        {
            t1 = t2;
            t2 = t2->next;
        }
        NObj->next = t2;
        t1->next = NObj;
    }
}

When I insert using the following objects

Obj("Brit", 6));
Obj("Germ", 2));
Obj("Cana", 7));
Obj("Zimb", 9));
Obj("Jama", 1));

I get the following from my Print function

 Jama
 Germ
 Zimb
 Cana
 Brit

Instead of

 Brit
 Cana
 Germ
 Jama
 Zimb

Note: The name parameter I'm inserting by is a char*

Upvotes: 2

Views: 155

Answers (2)

2785528
2785528

Reputation: 5566

I would guess another error is in this clause:

strcmp (NObj->name, head->name) 

which is in the loop started by:

while ((t2 != NULL) && strcmp(NObj->name, head->name) < 0 )
                                                ^^^^  ^^^  

I was expecting your code to compare the new object to t2->name(), trying to find the location before which you would insert the new object.

I think I am suggesting

while ((t2 != NULL) && strcmp(NObj->name, head->t2) < 0 )

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 81916

Your code has the conditional:

head->name >= Nobj->name

This compares two variables of type char *, which compares the two objects by the location of the string, not the contents of the string.

Instead, use std::string or strcmp().

I'm also concerned that you are not properly taking ownership of name in your Obj constructor, but you haven't shown any code for that...

Upvotes: 3

Related Questions