-2

我的代码有一些问题,需要看看您是否可以提供帮助。我正在尝试对我的 ROOM Struct 进行冒泡排序,代码如下。差不多,房间 1 名称:z ... 房间 2 名称:a,我想对这些进行排序,以便显示 A、B 等。

问题:当我输出链接列表时,这种排序会使某些节点消失。例如,在它对 Z > A 进行排序并放在 TOP 之后,当我去打印我的链接列表时,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;
    }
}

}

4

1 回答 1

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

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

编辑: 从函数参数中删除 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 */);
}
于 2012-12-06T12:35:43.273 回答