我的代码存在一些问题,需要了解您是否可以提供帮助。 我正在尝试对我的ROOM Struct进行冒泡排序,代码如下。 差不多,房间1名称:z ...房间2名称:a,我想要对它们进行排序,以便显示A,B等。
问题:当我输出链接列表时,这种类型会使某些节点消失...例如,在对Z>进行排序之后。 A,当我打印出我的链接列表时,A现在已经消失了
感谢您的帮助!
void sortRoomsByName(int count, ROOM *head)
{
int i;
int j;
for(i = count ; i > 1 ; i-- ) //outer loop
{
ROOM *temp;
ROOM *swap1;
swap1 = head;
for(j = 0 ; j < count-1 ; j++ ) //inner loop
{
if(strcmp(swap1->roomName,swap1->nextRoom->roomName)<0) //compares names and swaps
{
ROOM *swap2;
swap2 = swap1->nextRoom;
swap1->nextRoom = swap2->nextRoom;
swap2->nextRoom = swap1;
if(swap1 == head)
{
head = swap2;
swap1 = swap2;
}
else
{
swap1 = swap2;
temp->nextRoom = swap2;
}
}
temp = swap1;
swap1 = swap1->nextRoom;
}
}
}
答案 0 :(得分:0)
void sortRoomsByName(int count, ROOM *head)
{
int i;
int j;
for(i = 0 ; i < count - 1 ; i ++ ) //outer loop
{
ROOM *swap1;
swap1 = head;
for(j = 0 ; j < count - i - 1 ; j ++ ) //inner loop
{
if(strcmp(swap1->roomName,swap1->nextRoom->roomName)<0) //compares names and swaps
{
ROOM *swap2;
swap2 = swap1->nextRoom;
swap1->nextRoom = swap2->nextRoom;
swap2->nextRoom = swap1;
if(swap1 == head)
{
head = swap2;
}
}
else
{
swap1 = swap1->nextRoom;
}
}
}
如果没有进行交换,那么你必须跳到下一个NODE,我希望这有帮助...
修改强> 从函数参数中删除Head并使其成为全局或传递它,如下所示..
void sortRoomsByName(int count, ROOM **head)
{
int i;
int j;
for(i = 0 ; i < count - 1 ; i ++ ) //outer loop
{
ROOM *swap1;
swap1 = *head;
for(j = 0 ; j < count - i - 1 ; j ++ ) //inner loop
{
if(strcmp(swap1->roomName,swap1->nextRoom->roomName)<0) //compares names and swaps
{
ROOM *swap2;
swap2 = swap1->nextRoom;
swap1->nextRoom = swap2->nextRoom;
swap2->nextRoom = swap1;
if(swap1 == head)
{
*head = swap2;
}
}
else
{
swap1 = swap1->nextRoom;
}
}
}
int main (void)
{
sortRoomsByName(count /* your variable */, &head /* your head pointer */);
}