简体   繁体   中英

How to create a linked list use data read from file in C

I'm new to C, I want to read a data file that contains integers one at a line and add them into a linked list (I'm being lazy here so did not put the typedef into a .h file, but just put it at the top of my .c file). The structure of linked list is like:

typedef struct Node{
    int num;
    struct Node *next;
    
}Node;

Now I wrote some code like following, the .c file compiled but cannot display linked list properly. I don't know why this is happending but I'm guessing it's related to the while loop condition and fscanf()?

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

typedef struct Node{
    int num;
    struct Node *next;
    
}Node;

Node* createLinkedlist(FILE* input_file, char* filename1);
void displayList(Node *head);

int main() {
    char *filename1 = "data";
    int number;
    FILE *input_file;

    Node *head = NULL;
    head = createLinkedlist(input_file, filename1);
    displayList(head);
    return(0);
    

}


Node* createLinkedlist(FILE* input_file, char* filename1) {
    Node* head = NULL;
    Node* newNodePtr = NULL;
    Node* p = NULL;


    input_file = fopen(filename1, "r"); /*open input file, read data*/
    if(input_file == NULL) {
        printf("Cannot open %s", filename1);
        exit(EXIT_FAILURE);
    } 
    while(fscanf(input_file, "r") != EOF) { 
        /*Create individual Node*/
        newNodePtr = (Node*)malloc(sizeof(Node));
        if(newNodePtr == NULL){
            printf("The storage was NOT allocated.");
            exit(EXIT_FAILURE);
        } else {
            /*Create signle Node data*/
            fscanf(input_file, "%d\n", &(newNodePtr->num));
        }

        if(head == NULL){
            head = newNodePtr;
        }else {
            p = head;
            while(p->next != NULL) {
                p = p->next;
            }
            p->next = newNodePtr;
        }
        
    }
    return head;
    
}

void displayList(Node* head) {
    Node *p = head;

    while(p != NULL){
        printf("\t%d->", p->num);
        p = p->next;
    }
}

Can someone help me to figure out my problem? Thank you so much, I'm really struggled...

The main problem, you didn't assign NULL value to the proper value. After get the entry,you must write it:

newNodePtr->next = NULL;

if you don't do that, this doesn't work:

else {
        p = head;
        while(p->next != NULL) {
            p = p->next;
        }
        p->next = newNodePtr;
    }

Because if you don't assign NULL, you won't be able to find NULL value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM