GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

why this program does not print elements of linked list..???

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

using namespace std;

struct node{
int data;
struct node *next;
};
//struct node *head=NULL;
void push(struct node *head,int newdata)
{
struct node* new_node=(struct node*) malloc(sizeof(struct node));
    new_node->data=newdata;
    new_node->next=head;
    head=new_node;
   // printf("%d\n",nayanode->data);

}
void print(struct node *node1)
{
    while(node1 != NULL)
    {

        printf("%d",node1->data);
       // cout<<" ";
        node1=node1->next;

    }

}

int main()
{
   struct node *head1=NULL;
   push(head1,7);
   push(head1,34);
   push(head1,65);
   push(head1,87);
   push(head1,3);
   push(head1,77);
    print(head1);


   //cout<<1<<endl;

    return 0;
}

 

asked Aug 15, 2016 by Nishant Sinha

1 Answer

 

  1.  First error is in function push u have to give a reference(pointer to pointer) to the head.
  2. and inside the push function just put "*" before the head node 

       

3. when u r calling the function push is wrong

correct way of calling is push(&head1,7);  

use the symbol "&"  before the name of head node  

 

/* Given a reference (pointer to pointer) to the head of a list

   and an int,  inserts a new node on the front of the list. */

void push(struct node** head_ref, int new_data)

{

    /* 1. allocate node */

    struct node* new_node = (struct node*) malloc(sizeof(struct node));

  

    /* 2. put in the data  */

    new_node->data  = new_data;

  

    /* 3. Make next of new node as head */

    new_node->next = (*head_ref);

  

    /* 4. move the head to point to the new node */

    (*head_ref)    = new_node;

}

 

answered Aug 16, 2016 by intakhab Ali
edited Aug 17, 2016 by intakhab Ali
...