Reputation: 5416
To check a sample list imlpementation I tried the following code. But whenever i am trying to display the result it is getting inside a loop. I cant find where is it getting wrong.
#include<stdio.h>
#include<stdlib.h>
typedef struct linkedlist
{
int data;
struct linkedlist *next;
}node;
int main()
{
int ch,num;
node *head=NULL;
head=(node *)malloc(sizeof(node));
node *new=NULL;
new=(node *)malloc(sizeof(node));
node *temp=NULL;
temp=(node *)malloc(sizeof(node));
printf("\n1.Insert to list");
printf("\n3.Display the list");
printf("\n Enter Choice->");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\n Enter data->");
scanf("%d",&num);
new->data=num;
new->next=NULL;
head->next=new;
break;
case 3: temp=head;
while(temp!=NULL)
{
printf("\n %d",temp->data);
temp=temp->next;
}
break;
default:printf("Wrong Choice");
break;
}
return 0;
}
Upvotes: 0
Views: 104
Reputation: 1917
There are two mistakes here.
case 3: temp=head;
This is called a "memory leak."I suggest that you study pointers a bit more; they seem to be confusing you.
Upvotes: 1
Reputation: 750
Why do I feel like this is a homework question?
Here are some hints:
head
is allocated, but never initialized and this is where you start printing from. Frankly, I'm surprised it doesn't crash.
Your menu allows you to print the list OR enter a number, after which the program ends. I suspect you are entering a number, then running the program again to print out the list. The program state isn't preserved between runs.
Upvotes: 1
Reputation: 454960
I can see the following problems:
1) You are not looping with the options as a result user can do just one thing (either insert or display) in each run of your program. If he chooses to insert he can't display and if he chooses to display there isn't any list to display.
2) You need to create a new node every time you want to insert a new node in the list. Currently you are just changing the data of the same node (pointed to by new).
Upvotes: 0