Reputation: 55
There is no error when I compile the code, but the program crashes at runtime after two inputs. Maybe there is some logical error that I can not make out. I'm trying to insert nodes at the tail of linked lists while only maintaining head position.
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node *head;
//print the element of the lists
void print(){
printf("\nThe list from head to tail is as follows \n");
struct Node* temp = head;
while(temp!=NULL){
printf("\n %d ",(*temp).data);
temp = (*temp).next;
}
}
//insert a node at the tail of the linked list
void insert_at_tail(int data){
struct Node* temp = head;
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data=data;
new_node->next=NULL;
if(temp==NULL){
head=new_node;
}
else{
while(temp!=NULL){temp=temp->next;}
(*temp).next=new_node;
}
}
int main(){
head = NULL;
int i,data;
for(i=0;i<5;i++){
scanf("%d",&data);
insert_at_tail(data);
}
print();
return 0;
}
Upvotes: 1
Views: 184
Reputation: 73366
Maybe there is some logical error?
Yes!
Here:
while(temp!=NULL) { temp=temp->next; }
(*temp).next=new_node;
you will loop until temp
is actually NULL
and then request its next
member, so you are asking for next
of NULL
, thus you are asking for trouble (the program crashes)!
Try doing this instead:
while(temp->next != NULL) { temp=temp->next; }
where you are looping until temp
points to the last node of your list. With that change your code should work fine.
PS: Do I cast the result of malloc? No!
Upvotes: 5