I was writing a code in C for "A Singly Link List". In this code, I want to insert elements at the end of the list. It compiled fine. But during runtime, expected output is not coming. I am using gcc
as compiler. Whenever I am doing ./a.out
in terminal it just got hanged.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
struct list
{
int node;
struct list *next;
};
void insert(struct list *, int);
void print(struct list *);
int main()
{
struct list *mylist;
insert(mylist, 10);
insert(mylist, 20);
insert(mylist, 30);
insert(mylist, 40);
insert(mylist, 50);
insert(mylist, 60);
print(mylist);
return 0;
}
void print(struct list *head)
{
if(head==NULL)
return;
else
{
while(head->next!=NULL)
{
printf("%d\t",head->node);
head=head->next;
}
}
}
void insert(struct list *head, int value)
{
struct list *new_node;
new_node = (struct list *)malloc(sizeof(struct list));
//node Creation
new_node->node=value;
new_node->next=NULL;
//Adding Node to list
if(head==NULL)
{
head=new_node;
}
else
{
while(head->next!=NULL);
{
head=head->next;
}
head->next=new_node;
}
}
Here insert()
is the function which insert elements in mylist
linklist and print()
is a function which prints all values in the link list. Please help. I am not able to catch what mistake I have made.
I would suggest one more change, i.e. the prototypes of the functions should be like
void insert(struct list **, int);
void print(struct list **);
and the body should be changed accordingly. As you have done new memory allocations in insert and so you should not do a pass by value rather it should be pass by address then only it will work as intended.
Moreover, in print function the loop termination should be while(*head != NULL) instead of while((*head)->next != NULL) otherwise it will skip the last node.
Also you should store the first node into a tmp pointer after you invoke insert function first time and that tmp pointer should be passed into print function at the end. In your code you are passing the pointer to last node which is wrong. So, it should be like.
int main()
{
struct list *mylist=NULL, *tmp = NULL;
insert(&mylist, 10);
tmp = mylist; /* here */
insert(&mylist, 20);
insert(&mylist, 30);
insert(&mylist, 40);
insert(&mylist, 50);
insert(&mylist, 60);
/* At this point mylist is pointing to last node, so pass tmp which stores the first node */
print(&tmp);
return 0;
}
Problem is with following line,
while(head->next!=NULL);
It should be,
while(head->next!=NULL)
Remove semicolon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With