Reputation: 327
After inserting elements to my linked list, i would like to retrieve them.
This is the struct:
typedef struct node
{
int data;
struct node *next;
} Element;
typedef Element* ROW;
I start my list with :
void startRow(ROW *row){
*row = NULL;
}
After that, i use the function to insert at the end:
void insertEnd(ROW *row, int value){
if(*row==NULL){
*row = (ROW) (malloc(sizeof(Element)));
if(*row==NULL){
return;
}else{
(*row)->data = value;
(**row).next = NULL;
}
}
}
And to list the values, i use this function (I plan on removing recursion, just playing arround):
void listValues(ROW row){
if(row==NULL){
return;
}
printf("%d\n", row->data);
listValues(row->next);
}
I call it like this, but it only outputs the first element!
int main(){
ROW row;
startRow(&row);
insertEnd(&row, 10);
insertEnd(&row, 20);
listValues(row);
return 0;
}
Why? Shouldn't it output the complete list?
Upvotes: 0
Views: 53
Reputation: 11083
The problem is in the method insertEnd.
You should link the elements of the list not overide them :) like this :
void insertEnd(ROW *row, int value){
if(*row!=NULL){
ROW *lastElement = (ROW) (malloc(sizeof(Element)));
if(*lastElement==NULL){
return;
}else{
(*lastElement)->data = value;
(**lastElement).next = NULL;
(**row).next = lastElement;
}
} else {
*row = (ROW) (malloc(sizeof(Element)));
if(*row==NULL){
return;
}else{
(*row)->data = value;
(**row).next = NULL;
}
}
Like this you will link all your list elements.
Upvotes: 0
Reputation: 2769
*row is not null after the first insert. So the next insert never happens.
void insertEnd(ROW *row, int value){
if(*row==NULL){
printf("Inserting %d\n", value);
*row = (ROW) (malloc(sizeof(Element)));
if(*row==NULL){
return;
}else{
(*row)->data = value;
(**row).next = NULL;
}
}
}
Add a debug printf like this and it'll become obvious what's happening.
I think there are more fundamental problems though with the design!
You might want to keep a pointer to the start of the list around otherwise it'll be mighty difficult to find it again. And for a fast insert at the end you might want to keep a pointer to the end of the list as well.
I'm assuming that you are trying to figure this out for yourself, so I won't give you the answer :)
Upvotes: 3