-3

I am just learning about linked list. While I am trying to insert elements in linked list I am unable to print those inserted elements.

int main()
{
    int i,x,n; 
    struct node* head = NULL; 
    printf("Enter number of elements to insert into likedlist :"); 
    scanf("%d",&n); 
    printf("Enter elements: "); 
    for(i=0;i<n;i++) 
    {
        scanf("%d",&x);
        insert(head,x);
    }
    print(head);
} 

struct node* insert(struct node* head,int x)
{
    struct node* p = (struct node*)malloc(sizeof(struct node));
    p->data = x;
    p->next = NULL;
    if(head == NULL)
    {
        head = p;
        return head;
    }
    p->next = head;
    head = p;
    return head;
}

here I am adding the elements to a linked list by changing it's head node(insert_front).

void print(struct node* n)
{
    while(n != NULL)
    {
        printf("%d -> ",n->data);
        n = n->next;
    }
    printf("NULL");
}

So, what's wrong with this code. Output is like this

Sample Input:

 Enter number of elements to insert into likedlist :5
 Enter elements: 1 2 3 4 5

Sample Output:

NULL
Manoj Kare
  • 31
  • 7

1 Answers1

1

Read more about C programming (first some good tutorial book, then some reference site, and later refer to the C11 standard n1570). We cannot teach you it in a few paragraphs.

C uses a call-by-value evaluation strategy.

So, at least for newbies, it is conventionally recommended (but not required) to never use a formal argument as the left-side destination of some assignment, because any change to a formal argument is local to the function having that formal argument and does not impact the caller.

So, Compile with all warnings and debug info: gcc -Wall -Wextra -g with GCC. Use the debugger (e.g. gdb) to understand the behavior of your program (your bug is probably not in the code chunk you show us).

Ability to understand the behavior of an entire program, and to debug it, is an essential skill for developers. Both the compiler's warnings and the debugger can assist you in understanding the behavior of a program. See also http://norvig.com/21-days.html for a useful insight.

So the head formal argument in insert is a local copy of the actual argument from the caller.

In

if(head == NULL)
{
    head = p;
    return head;
}

you modify only that copy, not the original. So the head = p; above is completely useless (and confusing), you'll better just replace the block in braces above with simply return p;

We don't know how you call insert, and we cannot help more.

Perhaps insert should get the address of some pointer.... or perhaps your main should use the return value of it...

In your edited question, inside your main, replace

    insert(head,x); //WRONG

(which does not change the local head declared in main, even if insert is changing its first formal, because of call by value argument passing) with

    head = insert(head, x);
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547