I have an issue creating linked list: I don't know where I do an error in code, could you help me? Here's the code:
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 255
struct node {
int info;
struct node *next;
} *head = NULL;
int create(FILE **data){
char read[LENGTH];
printf("Write data file name: ");
scanf("%s", read);
*data = fopen (read, "r");
if (data == NULL) {
printf("Error reading given file.");
}
return 0;
}
int put_Symbols_into_list(FILE *data) {
struct node *new_node, *current;
char c;
printf("Data given: ");
while (!feof(data)){
new_node = (struct node*)malloc(sizeof (struct node));
c = fscanf(data, "%s", &new_node -> info);
printf("%s ", &new_node -> info);
if (head == NULL){
head = new_node;
current = new_node;
} else {
current -> next = new_node;
current = new_node;
}
}
}
int main() {
FILE *data;
struct node *n;
create(&data);
put_Symbols_into_list(data);
//display_List(n);
return 0;
}
Steps that I do: Read data file for string and put it new node; if HEAD node doesn't have any data in it, put the read data in it; else put it in new node. Cycle this until there is not data left in data file. You can create new data file and put data in there, like 1 0 1 1 2 3 4 5 6.
You are not putting current->next to NULL after adding a new node. That will make a problem when you try to go through a list, since you won't know where it ends. I hope that's the problem that you're facing with.
Also you're having redundant code, since current will always point to new_node after adding it. So you don't have to put it both in if and else block. Just an advice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With