我有两个简单的结构:
struct Address
{
char city[255];
};
typedef Address* AddressPtr;
struct Person
{
char fullName[255];
Address* address;
Person* next;
};
typedef Person* PersonPtr;
Person 结构形成链接列表,其中新元素被添加到列表的开头。我想要做的是对它们进行排序fullName
。起初我尝试交换链接,但我丢失了列表的开头,结果我的列表被部分排序。然后我决定通过交换节点的值来对列表进行排序。但我得到了奇怪的结果。对于名称列表:Test3, Test2, Test1
,我得到Test3, Test3, Test3
.
这是我的排序代码:
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);
}
排序完成后,节点值有点奇怪。
更新
这就是我交换链接的方式:
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;
}