I have a simple assignment that the professor wants us to do. Basically, to pull some numbers from a text file and load into a linked list. I do not want to understand the details in detail, but I have a basic question.
He provided us with this function:
INTLIST* init_intlist( int n ) { INTLIST *lst; lst = (INTLIST *)malloc(sizeof(INTLIST)); lst->datum = n; lst->next = NULL; return lst; }
This function is used to initialize the linked list with the first element. Then he asked us to define a function with this signature:
int insert_intlist( INTLIST *lst, int n )
So I assume that he just wants us to add to the linked list, so I tried this:
int insert_intlist( INTLIST *lst, int n ) { INTLIST* lstTemp; lstTemp = (INTLIST *)malloc(sizeof(INTLIST)); lstTemp->datum = n; lstTemp->next = lst; lst = lstTemp; free(lstTemp); }
So, what I thought was that it creates a temporary node, assigns a data value (Datum), and assigns the next pointer to indicate what the current pointer points to. Then I reassign the main pointer to this newly created temp node.
Thus, we have, for example, 2 nodes:
[New Temp Node] β [Prev Initialized Node]
When I look at the code, it looks great ...
Then basically I only have a function to print the list:
while (lst!=NULL) { printf("The value is:%d", lst->datum); lst=lst->next; }
The problem is that this only prints one digit (namely, the first digit that I read from the file, which, in my opinion, is the last on the list, or at least I thought it was the last on the list).
But it has to go on since I have 10 digits in the file. I know that the code is very dirty and I will clean it ... here is my main function if someone needs more information:
#include <stdio.h>
Here is intlist.h for those you might need:
#ifndef __intlist_h__ #define __intlist_h__ typedef struct intlist { int datum; struct intlist *next; } INTLIST; INTLIST *init_intlist( int n ); int insert_intlist( INTLIST *lst, int n ); void list_append(INTLIST *list, void *datum); INTLIST* list_front(INTLIST *list); void list_map( INTLIST *list, void (*f)(void *) ); void list_delete( INTLIST *list ); #endif