dimanche 1 août 2021

is there any error in display function , any error in else if statements when i tried to compile there are no errors but output has only two zeroes?

Question

#include <stdlib.h>

struct Asteroid
{
    int size;
    struct Asteroid *next;
};

typedef struct Asteroid *NODE;

NODE push(NODE head,int data);
NODE pop(NODE head);
void display(NODE P,NODE N);

int main()
{
    NODE head=NULL;
    NODE P=NULL ;
    NODE N=NULL;
    int i,data,n;

    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&data);
        P=push(head,data);

    }

    for(i=0;i<n;i++)
    {
        scanf("%d",&data);
        N=push(head,data);
    }

    display(P,N);
    return 0;

}

NODE push(NODE head,int data)
{
    NODE temp=(NODE)malloc(sizeof(struct Asteroid));
    if(temp==NULL)
    {
        exit(0);
    }
    temp->size=data;
    temp->next=head;
    head=temp;
    return head;
    }

NODE pop(NODE head)
{
    if(head==NULL)
    {
        printf("Stack is empty\n");
        return head;
    }
    NODE cur=head;
    head=head->next;
    free(cur);
    return head;
}


void display(NODE P,NODE N)
{
    int zero=0;
    int one=1;
    int count_coll=0;
    int count_noncoll=0;

    while(P!=NULL && N!=NULL)
    {
        if((P->size>0 && N->size>0) || (P->size<0 && N->size<0))
        {
            printf("%d\t",zero);
            P=pop(P);
            N=pop(N);
            count_noncoll++;
        }


        else if((P->size>0 && N->size<0) || (P->size<0 && N->size>0))
        {
            printf("%d\t",one);
            P=pop(P);
            N=pop(N);
            count_coll++;

        }



        else if(P->size==0)
        {
            P=pop(P);
        }

        else if(N->size==0)
        {
            N=pop(N);
        }
    }

    printf("%d\n",count_coll);
    printf("%d\n",count_noncoll);


}

this is the code part . The output part was to obtain zero if the asteroid(numbers)are of same sign and 1 if they are of opposite sign and to pop if zero appears. As you can see in the above image , the output as expected. But when i tried to run my program its showing no errors but the output is showing only " 0 0 ". i tried finding the errors but unable to figure out what is wrong. i think there is something wrong in the display function specifically the else if part . so please help me out with this.

Aucun commentaire:

Enregistrer un commentaire