0

I'm a Noob, trying to read in a dictionary file that contains one word per line, i.e. one\n two\n three\n, and insert the items in order into a linked list. I believe my code is otherwise working, but right now, it's outputting three, three, three (instead of one, two, three). I now believe my error is in my print function, so need to figure out how to traverse the linked list and print out the various node values.
// code modified from https://www.geeksforgeeks.org/linked-list-set-2-inserting-a-node/

#include <stdio.h> 
#include <stdlib.h> 

// A linked list node 
struct Node 
{ 
    const char *data; 
    struct Node *next; 
}; 

/* Given a reference (pointer to pointer) to the head 
of a list and an int, appends a new node at the end  */
void append(struct Node** head_ref, const char *new_data) 
{ 
    /* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 

    struct Node *last = *head_ref;  /* used in step 5*/

    /* 2. put in the data  */
    new_node->data  = new_data; 

    /* 3. This new node is going to be the last node, so make next of 
        it as NULL*/
    new_node->next = NULL; 

    /* 4. If the Linked List is empty, then make the new node as head */
    if (*head_ref == NULL) 
    { 
       *head_ref = new_node; 
       return; 
    } 

    /* 5. Else traverse till the last node */
    while (last->next != NULL) 
        last = last->next; 

    /* 6. Change the next of last node */
    last->next = new_node; 
    return; 
} 

// This function prints contents of linked list starting from head 
void printList(struct Node *node) 
{ 
    while (node != NULL) 
    { 
        printf("%s\n", node->data); 
        node = node->next; 
    } 
} 

/* Driver program to test above functions*/
int main() 
{ 
    // set up a file point to File to be opened
    FILE* fp;
    // holds contents of each line/word - as 1 word per line in dictionary per specs
    char buffer[255]; 

    fp = fopen("Xs.txt", "r");
    if (fp == NULL)
    {
        fprintf(stderr, "Could not open infile"); 
        return 2;
    }

    /* create an empty list */
    struct Node* head = NULL; 

    while(fgets(buffer, 255, (FILE*) fp)){
        //printf("%s", buffer);
        append(&head, buffer);
    }

    printList(head);
    fclose(fp);
    return 0; 
} 
Mike
  • 201
  • 2
  • 14
  • 1
    It's always educational to step through your code in a debugger to make sure it's behaving as intended. – tadman Mar 04 '19 at 18:24
  • Thanks xing, but your suggestion is still above my head in terms of being able to implement. – Mike Mar 04 '19 at 18:48
  • 2
    `new_node->data = strdup(new_data);` – Support Ukraine Mar 04 '19 at 18:48
  • In passing, I recommend that you read and understand [the question on why not to cast the return value of `malloc()` and family in C](/q/605845). You probably just want `struct Node *new_node = malloc(sizeof *new_node);` – Toby Speight Mar 04 '19 at 19:00

0 Answers0