I am not able to see the desired output.
Please let me know where I am missing a point.

#include<stdio.h>

struct node{
    int data;
    struct node *next;
};

void push_node(struct node *node, int data){
    struct node *new_node = (struct node *)malloc(sizeof(struct node));
    if(node!=NULL){
        new_node->data = data;
        new_node->next = node;
        node = new_node;
    }else{
        new_node->data = data;
        new_node->next = NULL;
        node = new_node;
    }
}

void display_node(struct node *node){
    struct node *temp =(struct node *)malloc(sizeof(node));
    temp = node;
    while(temp != NULL){
        printf("%d ",temp->data);
        temp = temp->next;
    }
}

int main(){
    struct node* head = NULL;
    push_node(head, 10);
    push_node(head, 2);
    display_node(head);
    getchar();
    return 0;
}

Edited 4 Years Ago by deceptikon: Changed to discussion thread

You need to pass the head of the linked list by reference rather than by value. That means functions need two stars, not one.

For this function, since you are adding the new node to the head of the list an if statement isn't necessary. But you see that it needs a pointer to a pointer so that this function can change the address of the caller's pointer.

void push_node(struct node **node, int data){
    struct node *new_node = (struct node *)malloc(sizeof(struct node));
    new_node->data = data;
    new_node->next = *node;
    *node = new_node;
}

 int main(){
struct node* head = NULL;
push_node(&head, 10); // <<< see change on this line
push_node(&head, 2); // <<< see change on this line
display_node(head);
getchar();
return 0;
}
This article has been dead for over six months. Start a new discussion instead.