gpt4 book ai didi

c - 链接列表的冒泡排序 请帮忙

转载 作者:行者123 更新时间:2023-11-30 20:41:32 26 4
gpt4 key购买 nike

我的代码遇到一些问题,需要看看您是否可以提供帮助。我正在尝试对我的房间结构进行冒泡排序,代码如下。差不多,房间 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;
}
}

}

最佳答案

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;
}
}
}

如果没有完成交换,那么你必须跳转到下一个节点,我希望这会有所帮助......

编辑:从函数参数中删除 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 */);
}

关于c - 链接列表的冒泡排序 请帮忙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13741291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com