C program to count odd and even numbers in linked list

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
//Creating structure
struct node
{
    int data;
    struct node *link;
}*first=NULL;

struct node * create(struct node *);
void oddeven(struct node *);

//main function
int main()
{
    printf("\nEnter elements to create linked list\n");
    first=create(first);
    printf("\nLinked list created!\n");
    oddeven(first);
    return 0;
}

//function to create linked list
struct node * create(struct node *first)
{
    struct node *new_node;
    int choice=0;

    do
    {
        new_node=(struct node *)malloc(sizeof(struct node));
        printf("\nEnter  an element\n");
        scanf("%d",&new_node->data);
        new_node->link=NULL;
        if(first==NULL)
            first=new_node;
        else
        {
            new_node->link=first;
            first=new_node;
        }
        printf("\nEnter 1 to continue, 0 to stop\n");
        scanf("%d",&choice);
    }while(choice==1);
    return first;
}

//function to count odd and even numbers in the linked list
void oddeven(struct node * first)
{
    struct node *temp=NULL;
    int odd=0,even=0;
    if(first==NULL)
        printf("\nLinked list does not exist\n");
    else if(first->link==NULL)
    {
        if(first->data%2==0)
            ++even;
        else
            ++odd;
    }
    else
    {
        temp=first;
        while(temp!=NULL)
        {
            if(temp->data%2==0)
            {
                ++even;
                temp=temp->link;
            }
            else
            {
                ++odd;
                temp=temp->link;
            }
        }
    }
    printf("\nOdd no. count=%d\nEven no. count=%d\n",odd,even);
}

OUTPUT:

TRIAL 1:

Enter elements to create linked list

Enter  an element
10

Enter 1 to continue, 0 to stop
1

Enter  an element
11

Enter 1 to continue, 0 to stop
1

Enter  an element
12

Enter 1 to continue, 0 to stop
1

Enter  an element
13

Enter 1 to continue, 0 to stop
1

Enter  an element
14

Enter 1 to continue, 0 to stop
1

Enter  an element
15

Enter 1 to continue, 0 to stop
0

Linked list created!

Odd no. count=3
Even no. count=3

TRIAL 2 :

Enter elements to create linked list

Enter  an element
10

Enter 1 to continue, 0 to stop
0

Linked list created!

Odd no. count=0
Even no. count=1


Popular Posts