dimanche 13 septembre 2020

cannot print a statement inside if after data assignment to a structure variable in linked list in c

when i am trying to take multiple test cases my linked list code stops after the first test case,so for debugging i put some statements and found a weird thing that inside if in my insert function "hello3" gets printed but not "hello4" and "hello5" This question was taken from hackerrank,link-https://ift.tt/3hoctct

#include <stdio.h>  
typedef struct Node
{
    int data;
    struct Node* next;
}Node;

Node* insert(Node *head,int data)
{
    printf("hello1");
    //Complete this function
    Node *current,*ptr;
    current=(Node*)malloc(sizeof(Node));
    current->next=NULL;
   printf("hello2");
    if(head==NULL)
    {
        printf("hello3");//prints hello3
        ptr->data=data;
        printf("hello4");//cannot print hello4
        ptr=current;
         head=ptr;
         printf("hello5");//cannot print hello5
    }
    else
    {
        ptr=head;
        while(ptr->next!=NULL)
        {
            ptr=ptr->next;
        }
        ptr->next=current;
        current->data=data;
        ptr=current;
    }
    return head;
}

void display(Node *head)
{
    Node *start=head;
    while(start)
    {
        printf("%d ",start->data);
        start=start->next;
    }
}
int main()
{
    int T,data;
    scanf("%d",&T);
    Node *head=NULL;    
    while(T-->0){
        scanf("%d",&data);
        head=insert(head,data);
    }
  display(head);
        
}

Aucun commentaire:

Enregistrer un commentaire