This is not working.where is the problem? Code: /// Inserting a new item in last position in linked list #include<stdio.h> #include<stdlib.h> struct node{ int data; struct node* next; }; struct node* head; void insert_at_last(int x) { struct node* temp; struct node* temp2; if(head==NULL) { temp=(struct node*)malloc(sizeof(struct node)); temp->data=x; temp->next=NULL; head=temp; } else { temp=(struct node*)malloc(sizeof(struct node)); temp=head; while(temp!=NULL) { temp=temp->next; } temp2=(struct node*)malloc(sizeof(struct node)); temp2->data=x; temp=temp2; temp2->next=NULL; } } void print() { struct node* temp; temp=head; printf("List is: "); while(temp!=NULL) { printf("%d",temp->data); temp=temp->next; } printf("\n\n"); } int main() { head=NULL; int i,n,x; printf("How many data?"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Input data: "); scanf("%d",&x); insert_at_last(x); print(); } return 0; }
What's it doing wrong? What input do you give it? What output do you expect? What output did you get? Or is it a compile-time problem rather than a runtime problem? If so, what errors did you get? What operating system and compiler are you using? Include versions of both; there is more than one option. I can see you're still a beginner - using scanf for input. Drop this as soon as your teacher lets you. Use fgets and parse the string instead. The first malloc in your else block is unnecessary. It achieves nothing but a memory leak. Don't use variable names like temp and temp2. This makes the code really unreadable. Use sensible names like list_iterator and new_node instead, then it will be much clearer. Actually I think the problem could be your while loop. You don't want to step off the last node onto the NULL, which is what you're doing (the while doesn't terminate until list_iterator, sorry, "temp", is NULL). Let me guess - you got a segfault, right? You need to check for when temp->next is NULL, not temp itself. Then after setting up the new node (temp2), assign temp->next to temp2. Or list_iterator->next=new_node; <== see how that is self-documenting and much easier to read than all this temp nonsense?