首页 > 解决方案 > 为什么我在链表中​​的排序功能(通过交换数据进行排序)不起作用

问题描述

当我运行此函数时,它会返回所有数字而不进行任何排序?当我使用 for 循环时它工作得非常好?谁能告诉我哪里出错了?

struct node //structure node 
{
    int info;
    struct node *link;
};

void sort(struct node *start)       //function for sorting
{
    struct node *p,*temp;
    int r;
    p = start;
    temp = p->link;
    while(p != NULL)      //first loop
    {
        while(temp != NULL)    //second loop
        {
            if(temp->info < p->info)
            {
                r=p->info;
                p->info = temp->info;
                temp->info = r;
            }
            temp = temp->link;
        }
        p = p->link;
    }
}

标签: c++sorting

解决方案


在外while循环的第一次迭代之后,temp将是NULL. 但是,temp没有设置在内while循环之外,因此它将保持NULL. start->info只有不是最小的数字才会改变。

将赋值temp = p->link 移到外部 while 循环中:

void sort(struct node *start)
{
    struct node *p,*temp;
    int r;
    p = start;
    while(p != NULL)
    {
        temp = p->link;        // <-------
        while(temp != NULL)
        {
            if(temp->info < p->info)
            {
                r=p->info;
                p->info = temp->info;
                temp->info = r;
            }
            temp = temp->link;
        }
        p = p->link;
    }
}

推荐阅读