簡體   English   中英

C:按字母順序對列表進行排序

[英]C: Sorting a list alphabetically

我的項目有問題。 我編寫了一個函數,該函數從文件中讀取結構,然后按字母順序對其進行排序,然后寫回到文件中。 可以讀取文件並將其放回去,因為我在其他功能中使用了相同的代碼,因此效果很好。 我的排序有問題,因為使用此功能后,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);
}

提前非常感謝您的幫助!

這里有幾處錯誤,讓我們看一下這個循環:

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

您為wsk2分配了一些wsk2 ,然后再也不使用它。 您嘗試通過比較word的地址(而不是該地址的值)來比較word 而且我完全看不到您如何重新訂購商品。

要比較兩個字符串,您需要使用strcmp ,還需要確定想要它們的順序。

其次,您不能僅通過瀏覽一次就對列表進行排序。 您將必須具有嵌套的循環,以將項目彼此進行比較,並可能執行多次移動才能將項目移到適當的位置。

而且,對鏈接列表中的項目進行重新排序(不少於單個鏈接)非常困難,並且充滿了必須考慮的邊緣條件。 當您要交換兩個項目時,應考慮將指針移至wordcategory 可能看起來像:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM