c - linked list print function is not working -
this program runs without error doesn't print anything. couldn't figure out error.
i'm learning data structure in c, practice 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; }
your list empty because push returned value not used
your main should 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 can pass list reference , time code 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; }
Comments
Post a Comment