回覆列表
  • 1 # 使用者834195712159

    程式碼示例:

    #include <stdio.h>

    #include <string.h>

    #include <stdlib.h>

    const int MAXSIZE = 128; // 每個單詞不超過128個字元

    typedef struct node {

    char word[MAXSIZE];

    int size;

    struct node *next;

    }*List,*pNode;

    List Init() {

    List head;

    head = (pNode)malloc(sizeof(struct node));

    head->size = 0;

    head->word[0] = "\0";

    head->next = NULL;

    return head;

    }

    char *toLower(char s[]) { // 小寫變大寫

    int i = 0;

    while(s[i]) {

    if(s[i] >= "A" && s[i] <= "Z")

    s[i] += "a" - "A";

    ++i;

    }

    return s;

    }

    void Add(List head,char s[]) { // 新增到連結串列中

    pNode p = head;

    char t[MAXSIZE];

    strcpy(t,toLower(s));

    while(p->next) {

    if(strcmp(p->next->word,t) == 0) {

    ++p->next->size;

    return;

    }

    p = p->next;

    }

    p->next = (pNode)malloc(sizeof(struct node));

    strcpy(p->next->word,t);

    p->next->size = 1;

    p->next->next = NULL;

    }

    void Sort(List head) { // 根據bai各個詞的數量排序(大到小)

    pNode p,q,qt;

    char ct[MAXSIZE];

    int it;

    for(p = head; p->next; p = p->next) {

    qt = p;

    for(q = p->next; q->next; q = q->next) {

    if(strlen(qt->next->word) < strlen(q->next->word))

    qt = q;

    }

    if(p != qt) {

    strcpy(ct,p->next->word);

    strcpy(p->next->word,qt->next->word);

    strcpy(qt->next->word,ct);

    it = qt->next->size;

    qt->next->size = p->next->size;

    p->next->size = it;

    }

    }

    }

    void Show(List head, int n,FILE *fp) { // 顯示前n個

    int i;

    pNode p = head->next;

    for(i = 0; p; ++i) {

    fprintf(fp,"%s\n",p->word);

    if(i < n) printf("%3d : %s\n",p->size,p->word);

    p = p->next;

    }

    }

    int main() {

    char word[MAXSIZE];

    List head = Init();

    FILE *fin = fopen("data.txt","rt");

    FILE *fout = fopen("result.dat","wt");

    List list = Init();

    if(fin == NULL || fout == NULL) {

    printf("不能開啟資料檔案。\n");

    return 1;

    }

    while(fscanf(fin,"%s",word) == 1)

    Add(head,word);

    fclose(fin);

    Show(head,3,fout);

    fclose(fout);

    return 0;

    }

  • 中秋節和大豐收的關聯?
  • 影子前鋒是幹什麼的?需要怎樣的身體條件?