Can't create separate list
I have a problem creating a linked list: I don't know where I am making a mistake in the code, can you please 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;
}
The steps I am doing are: read the data file for the string and put it in a new node; if the HEAD node does not contain any data in it, put the read data into it; otherwise put it in a new node. Loop this until there is no data left in the data file. You can create a new data file and put data there, for example 1 0 1 1 2 3 4 5 6
.
source to share
You don't put current->next
in NULL after adding a new node. This will cause a problem when trying to browse the list, since you will not know where it ends. I hope this is the problem you are facing.
Also you have redundant code as current
it will always point to new_node
after adding it. So you don't need to put it in the if and else block. Just a tip.
source to share
You forgot to make the last node a NULL dot . This will be extremely important when you try to go through your list and display it.
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, "%d", &new_node -> info);
printf("%d ", new_node->info);
if (head == NULL){
head = new_node;
current = new_node;
} else {
current->next = new_node;
current = new_node;
new_node->next = NULL; // << added
}
}
return 0;
}
source to share
In addition to the above answers, you are declaring current
as a local variable in put_Symbols_into_list
rather than initializing current
. Every time you log out put_Symbols_into_list
, the value current
may be lost. You either need to declare current
as static struct node *current
, pass it as a parameter, or declare it globally. I would prefer a static approach in this setup.
source to share