Reputation: 65
This program runs without error but it doesn't print anything. I couldn't figure out the error.
I'm learning data structure in C, is this a good practice to learn data structure?
Thanks in advance!!!!!!
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}list_node;
list_node* push(list_node* head_r, int new_data)
{
list_node* new_Node = (list_node*)malloc(sizeof(list_node));
new_Node->data = new_data;
new_Node->next = head_r;
head_r = new_Node;
return head_r;
}
void Print(list_node* head_r)
{
while(head_r)
{
printf("%d\n", head_r->data);
head_r = head_r->next;
}
}
int main()
{
list_node* l_list = NULL;
push(l_list, 1);
push(l_list, 2);
push(l_list, 6);
push(l_list, 8);
push(l_list, 7);
push(l_list, 3);
push(l_list, 4);
printf("Given linked list \n");
Print(l_list);
return 0;
}
Upvotes: 0
Views: 79
Reputation: 4906
Your list is empty because push returned value is not used
Your main should like this:
int main()
{
list_node* l_list = NULL;
l_list = push(l_list, 1);
l_list = push(l_list, 2);
l_list = push(l_list, 6);
l_list = push(l_list, 8);
l_list = push(l_list, 7);
l_list = push(l_list, 3);
l_list = push(l_list, 4);
printf("Given linked list \n");
Print(l_list);
return 0;
}
or you can pass list by reference and for this time your code look like this:
void push(list_node** head_r, int new_data)
{
list_node* new_Node = (list_node*)malloc(sizeof(list_node));
new_Node->data = new_data;
new_Node->next = *head_r;
*head_r = new_Node;
}
int main()
{
list_node* l_list = NULL;
push(&l_list, 1);
push(&l_list, 2);
push(&l_list, 6);
push(&l_list, 8);
push(&l_list, 7);
push(&l_list, 3);
push(&l_list, 4);
printf("Given linked list \n");
Print(l_list);
return 0;
}
Upvotes: 3
Reputation: 1153
Change the lines in the main
function for these:
l_list = push(l_list, 1);
l_list = push(l_list, 2);
l_list = push(l_list, 6);
l_list = push(l_list, 8);
l_list = push(l_list, 7);
l_list = push(l_list, 3);
l_list = push(l_list, 4);
You were returning a new node with push
but not saving anywhere, so your list in main
was always empty.
Upvotes: 2