Click here to Skip to main content
15,896,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am trying to add node at the starting of linked-list my code all the time just printing the last value which i entered what is the problem can any one clear it.

What I have tried:

#include <stdio.h>

struct node
{
    int data;
    struct node *next;

};

typedef struct node node ;
node *head;

void create(int num);
void display();

main()
{
    int num,i,n;

    printf("enter the nno of node to create : ");
    scanf("%d",&n);

    for(i=0;i<n;++i)
    {
        printf("enter data for node %d= ",i+1);
        scanf("%d",&num);
        create(num);
        display();
    }
}

void create(int num)
{
    head=NULL;
    node *temp;
    temp=(node*)malloc(sizeof(node));
    temp->data=num;
    temp->next=head;
    head=temp;
    return;
}
void display()
{
    node *temp1;
    temp1=head;

    while(temp1!=NULL)
    {
        printf("data : %d-> ",temp1->data);
        temp1=temp1->next;
    }
    return;
}
Posted
Updated 27-Jul-16 8:25am
v2
Comments
jeron1 27-Jul-16 12:59pm    
head=NULL;
node *temp;
temp=(node*)malloc(sizeof(node));
temp->data=num;
temp->next=head; <== temp->next = head , which is always NULL

You are setting the head to NULL inside create() and assign that (now NULL) to next:
void create(int num)
{
    // This sets head to NULL. Remove it.
    head=NULL;
    node *temp;
    temp=(node*)malloc(sizeof(node));
    temp->data=num;
    // This will be NULL because head has been set to NULL above
    temp->next=head;
    head=temp;
    return;
}

So remove the indicated line and initialise head when declaring it:
C++
node head = NULL;
 
Share this answer
 
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

You have got an answer in solution 1.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.

[Update]
In complement to Solution 1, put this line
C++
node head = NULL;
at beginning of main.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900