Reputation: 57
I have written below program which creates a new linked list and prints its elements. The problem I face here is that when i print the values, only the value of last node gets printed and that too several times. Please have a look and tell me what am i doing wrong in this program.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *link;
}*head=NULL;
void print()
{
struct node *temp=NULL;
temp=head;
while(temp!=NULL)
{
printf("%d", temp->data);
temp=temp->link;
}
printf("NULL");
}
void create_list()
{
int value;char ch;
struct node *new_node=(struct node*)malloc(sizeof(struct node*));
struct node *current=NULL;
printf("before do\n");
do{
printf("enter the data \n");
scanf("%d", &value);
new_node->data=value;
new_node->link=NULL;
if(head==NULL)
{
head=new_node;
current=new_node;
}
else
{
current->link=new_node;
current=new_node;
}
printf("do you want to create another node \n");
ch=getche();
}while(ch=='Y');
}
int main()
{
create_list();
print();
getchar();
return 0;
}
Input and output:
enter the data
2
do you want to create another node
Y
enter the data
3
do you want to create another node
Y
enter the data
4
do you want to create another node
Y
enter the data
5
do you want to create another node
N
55555555555555555555
55555555555555555555
55555555555555555555
55555555555555555555
55555555555555555555
Upvotes: 0
Views: 107
Reputation: 920
The problem is that you are adding value to the same node. And by your program there will be only one node, linked to the same node. The while(temp!=NULL)
Fails due to the same reason. temp->link
points to the same temp
. That you are getting the same output many (infinite ) times.
Upvotes: 1
Reputation: 747
You are creating only one node:
struct node *new_node=(struct node*)malloc(sizeof(struct node*));
Above line is before do..while loop. It should be inside the loop.
Upvotes: 1