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;
}

Recommended Answers

All 2 Replies

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;
}

Hi Ancient Dragon
Thanks for your reply.
Now its working fine :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.