C++: incorrect swapping of nodes in linked list

Posted by Dragon on Stack Overflow See other posts from Stack Overflow or by Dragon
Published on 2013-11-11T15:42:46Z Indexed on 2013/11/11 15:53 UTC
Read the original article Hit count: 181

Filed under:

I have 2 simple structures:

struct Address
{
    char city[255];
};
typedef Address* AddressPtr;

struct Person
{
    char fullName[255];
    Address* address;
    Person* next;
};
typedef Person* PersonPtr;

The Person structure forms the Linked list where new elements are added to the beginning of the list. What I want to do is to sort them by fullName. At first I tried to swap links, but I lost the beginning of the list and as a result my list was sorted partially. Then I decided to sort list by swapping the values of nodes. But I get strange results. For a list with names: Test3, Test2, Test1, I get Test3, Test3, Test3.

Here is my sorting code:

void sortByName(PersonPtr& head)
{
    TaskPtr currentNode, nextNode;
    for(currentNode = head; currentNode->next != NULL; currentNode = currentNode->next)
    {
        for(nextNode = currentNode->next; nextNode != NULL; nextNode = nextNode->next)
        {
            if(strcmp(currentNode->fullName, nextNode->fullName) > 0)
            {
                swapNodes(currentNode, nextNode);
            }
        }

    }
}

void swapNodes(PersonPtr& node1, PersonPtr& node2)
{
    PersonPtr temp_node = node2;
    strcpy(node2->fullName, node1->fullName);
    strcpy(node1->fullName, temp_node->fullName);

    strcpy(node2->address->city, node1->address->city);
    strcpy(node1->address->city, temp_node->address->city);
}

After the sorting completion, nodes values are a little bit strange.

UPDATED

This is how I swapped links

void swapNodes(PersonPtr& node1, PersonPtr& node2)
{
    PersonPtr temp_person;
    AddressPtr temp_address;

    temp_person = node2;
    node2 = node1;
    node1 = temp_person;

    temp_address = node2->address;
    node2->address = node1->address;
    node1->address = temp_address;
}

© Stack Overflow or respective owner

Related posts about c++