C:按字母顺序对列表进行排序

时间:2014-01-18 23:57:38

标签: c list sorting

我的项目有问题。我编写了一个从文件中读取结构的函数,按字母顺序对其进行排序并写回文件。从文件读取并将其放回到它是可以的,因为我在其他功能中使用相同的代码并且它工作完美。 我的排序有问题,因为在使用此功能后,txt文件为空白。 它正在开发函数之外的结构:

typedef struct baseofwords                                
    {
        char *word;
        char *category;
        struct baseofwords* next;
    } base;

这是我的功能:

void SORTING (base **head)
{
char word[30];
char category[20];
FILE *fp;
if ((fp = fopen("baza.txt", "r"))==NULL)
    {printf("Error while opening the file!");
    exit(EXIT_FAILURE);}
else
    {
    while(!feof(fp))
        {
        fscanf(fp,"%s %s \n", word, category);
        base *wsk = *head;
        base *new = malloc (sizeof(base));
        new -> next = NULL;
        new -> word = strdup(word);
        new -> category = strdup(category);
        if(wsk == NULL)
            {
            new -> next = *head;
            *head = new;
            }
        else
            {
            while(wsk -> next != NULL)
            wsk = wsk -> next;
            wsk -> next = new;
            }
        }
    }
fclose(fp);
//==========================================up until here it works, problem must be down there


base *newHead = NULL;
base *wsk1, *wsk2, *tmp;
wsk1 = tmp = *head;
wsk2 = NULL;
while(tmp->next)
    { if (tmp->next->word > wsk1->word)
        { wsk2 = tmp;
        wsk1 = tmp->next;
        }
    tmp = tmp->next;
    }
if (wsk2) wsk2->next = wsk1->next;
else *head = wsk1->next;
wsk1->next = newHead;
newHead = wsk1;
*head = newHead;


//======================this part is okay again
if ((fp = fopen("base.txt", "w"))==NULL)
    {printf("Error while opening file!");
    exit(EXIT_FAILURE);}
else
    {base *wsk = *head;
    while (wsk->next != NULL)
    {fprintf(fp, "%s %s\n", wsk->word, wsk->category);
    wsk=wsk->next;}
    }fclose(fp);
}

非常感谢您提前寻求帮助!

1 个答案:

答案 0 :(得分:1)

这里有几件事是错的,让我们来看看这个循环:

while(tmp->next)
    { if (tmp->next->word > wsk1->word)
        { wsk2 = tmp;
        wsk1 = tmp->next;
        }
    tmp = tmp->next;
    }

您将某些内容分配给wsk2,然后再从不使用它。您尝试通过比较word的地址(而不是该地址的值)来比较strcmp。我根本没有看到你如何重新订购商品。

要比较两个字符串,您需要使用word,还需要确定所需的顺序。

其次,您不能仅通过单步执行一次就可以对列表进行排序。您将不得不使用嵌套循环来比较项目,并执行多项移动以将项目移动到位。

对链接列表中的项目进行重新排序(单个链接不少),相当困难,并且充满了必须考虑的边缘条件。当您想要交换两个项目时,应该考虑将指针移动到categoryvoid swapbases( base *it1, base *it2 ) { base tmp= * it1 ; it1-> word= it2-> word, it1-> category= it2-> category ; it2-> word= tmp.word, it2-> category= tmp.category ; } 。这可能看起来像:

int swaps ;
for ( swaps= 1 ; ( swaps ) ; )
{
  swaps= 0 ;
  for ( tmp= head ; ( tmp-> next ) ; tmp= tmp-> next )
  {
     if ( strcmp( tmp-> word, tmp-> next-> word ) < 0 )
       { swapbases( tmp, tmp-> next ) ;  swaps ++ ; }
  }
}

然后编写一些循环,逐步查找项目。有一种叫做冒泡的可怕的东西:

{{1}}