c - Linked List elements not getting displayed -


this program in c inserts linked list @ end. when try print list elements, nothing displayed. here code :

#include<stdio.h> #include<stdlib.h> struct node {     int data;     struct node *next; }; void insert(struct node *, int); int main(void) {     struct node *head = null, *current;     int n, i, x, data;     scanf("%d", &n);     for(i = 0; < n; i++)     {         scanf("%d", &data);         insert(head, data);     }     current = head;     while(current != null)     {         printf("%d ", current->data);         current = current->next;     } } void insert(struct node *head, int data) {     struct node *newnode, *current = head;     newnode = (struct node *)malloc(sizeof(struct node));     newnode->data = data;     newnode->next = null;     if(head == null)     {         head = newnode;     }     else     {         while(current->next != null)         {             current = current->next;         }         current->next = newnode;     } } 

i cannot understand might issue. please help.

here, while passing head pointer insert() function, not being updated in main() function.

so, either declare head pointer global or return head pointer , update in main() function.

in below code had taken head pointer global , removed head pointer parameter insert() function.

here code :-

#include<stdio.h> #include<stdlib.h> struct node {     int data;     struct node *next; }; struct node *head=null; void insert(int); int main(void) {     struct node  *current;     int n, i, x, data;     clrscr();     scanf("%d", &n);     for(i = 0; < n; i++)     {     scanf("%d", &data);     insert(data);     }     current = head;     while(current != null)     {     printf("%d \n", current->data);     current = current->next;     }     getch();     return 0; } void insert(int data) {     struct node *newnode, *current = head;     newnode = (struct node *)malloc(sizeof(struct node));     newnode->data = data;     newnode->next = null;     if(head == null)     {     head = newnode;     }     else     {     while(current->next != null)         {             current = current->next;         }         current->next = newnode;     } } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -