代码之家  ›  专栏  ›  技术社区  ›  Diksha

在C语言中将文本文件转换为单链表时,每次插入时头部都会更新

  •  2
  • Diksha  · 技术社区  · 6 年前

    如问题所述,我想将文本文件转换为链表。当我从数组中读取字符串元素时,它工作得很好,但在从文件中执行相同操作时,会产生更新头的问题。以下是我尝试过的。。。

    #include<string.h>
    #include<stdio.h>
    #include<stdlib.h>
    
    //creating structure
    typedef struct node {
        char *word;
        struct node *next;
    }node;
    
    //function for creating a node
    node *createnode(char *wrd){
        node *temp1;
        temp1 = (node*)malloc(sizeof(node));
        temp1->word = wrd;
        temp1->next = NULL;
        return temp1;
    }
    
    //function for creating and adding new node to linked list
    node *creat(node *head, char *wrd){
        node *temp, *p;
        temp = createnode(wrd);
        if(head == NULL){
            head = temp;
        }else{
            p = head;
            while(p->next != NULL){
                p = p->next;
            }
            p->next = temp;
    
            printf("p->word from creat method: %s ADDR: %p HEAD: %s \n", p->word, 
            p->next,head->word);
        }
        return head;
    }
    
    //traverse the list and display each node
    node *show(node *head){
        node *p;
        p=head;
        while(p != NULL){
            printf("from show method: %s", p->word);
            p = p->next;
            printf("\n");
        }
        printf("\n");
    }
    
    
    int main()
    {
         node *head = NULL;
         /* Character array to read the content of file */
         char sWord[20];
         /* Pointer to the file */
         FILE *fp;
    
         /* Opening a file in r mode*/
         fp= fopen ("hw10data.txt", "r");
    
         while( fscanf(fp, "%s", sWord) != EOF )
            {
            head = creat(head, sWord); //create list
            }
         fclose(fp);
    
         show(head);
         return 0;
    }
    

    我不知道为什么每次插入时头部都在更新。任何帮助都将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Stephan Lechner    6 年前

    改变的不是名单的头条;只需将值读入本地数组 sWord ,然后将其传递给 creat createnode -功能。其中,您只需分配一个指针,但不复制 ;因此,所有节点内容将指向相同的内存地址,即 ;当您读入新值时,所有节点内容都将指向该新值。所以“头”似乎变了。实际上,所有节点都将显示相同的内容。。。

    要克服此问题,请在中编写以下内容 createnode :

    // temp1->word = wrd;
    temp1->word = strdup(wrd);
    

    或者,如果 strdup 不可用:

    temp1->word = malloc(strlen(wrd)+1);
    strcpy(temp1->word,wrd);