Reputation: 774
I wrote this code for a user to enter the number of nodes they want in a list, as well as the element for each node. My error occurs only once I try printing the values of the list. It seems as though I am only printing the first value of the list. Either that or I was unsuccessful in assigning the data to the list.
Note "list.h" only include the stdio and stdlib libraries, as well as the struct definition. Which just holds data and a pointer to the same struct.
#include "list.h"
struct node *head = NULL;
void print_data(){
struct node* temp;
temp = head;
printf("\n\n");
while(temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
}
void insert(data){
struct node *temp = malloc(sizeof(struct node));
struct node *p;
temp->data = data;
temp->next = NULL;
if( head == NULL ){
head = temp;
}else{
p = head;
while( p->next != NULL){
p = p->next;
p->next = temp;
}
}
}
int main(){
int i, amount, element;
printf("\nEnter Amound of Nodes: \n");
scanf(" %d", &amount);
for( i = 0; i < amount; ++i){
printf("\nEnter Node #%d amount ", i + 1);
scanf(" %d", &element);
insert(element);
}
print_data();
}
Upvotes: 1
Views: 742
Reputation: 131
I would normally push to the head of the list, rather than the tail. ie:
my_struct_t tmp->next = list_head;
list_head = tmp;
That way you avoid looping to the end of the list each time you need to add to the list.
Upvotes: 0
Reputation: 26800
In the while
of the insert
function, you are assigning temp
to every element from the second element onwards. You have to first reach to the end of the list and only then add it to the list. So move the assignment outside the while
loop.
Upvotes: 1
Reputation: 12732
Your insertion is wrong. Assuming you want to insert node at the last of linked list. but your code inserts node at the beginning of the list without properly handling the rest of the list. Hence your rest of the list will be lost.
while( p->next != NULL){
p = p->next;
p->next = temp;
}
Should be
while( p->next != NULL){
p = p->next;
}
p->next = temp;
Upvotes: 2