0

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
timrau
  • 22,578
  • 4
  • 51
  • 64
Kung-fu-panda
  • 47
  • 1
  • 1
  • 8
  • The 90's called, they want their `conio.h` back. – Maxime Chéramy Apr 28 '14 at 09:52
  • 3
    This is wrong: `malloc(sizeof(struct node*));` Use `malloc(sizeof(struct node));`. And don't cast return value of `malloc` in C. What you are getting as output is not the last value you input, it is just the garbage. – 0xF1 Apr 28 '14 at 09:53

2 Answers2

1

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.

rockoder
  • 747
  • 11
  • 23
1

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.

jsaji
  • 900
  • 1
  • 15
  • 31