C Program to Modify the Linked List such that All Even Numbers appear before all the Odd Numbers in the Modified Linked List

This C Program modifies the linked list such that all even numbers appear before all the odd number in the modified linked list.

Here is a source code of the C program that modifies the linked list such that all even numbers appear before all the odd number. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*

* C Program to Modify the Linked List such that All Even Numbers

* appear before all the Odd Numbers in the Modified Linked List

*/

#include <stdio.h>

#include <stdlib.h>

struct node

{

int num;

struct node *next;

};

void create(struct node **);

void generate_evenodd(struct node *,struct node**);

void release(struct node **);

void display(struct node *);

int main()

{

struct node *p = NULL,*q = NULL;

int key, result;

printf("Enter data into the list\n");

create(&p);

printf("Displaying the nodes in the list:\n");

display(p);

generate_evenodd(p,&q);

printf("Displaying the list with even and then odd:\n");

display(q);

release(&p);

return0;

}

void generate_evenodd(struct node *list,struct node **head)

{

struct node *even = NULL,*odd = NULL,*temp;

struct node *reven,*rodd;

while(list != NULL)

{

temp =(struct node *)malloc(sizeof(struct node));

temp->num = list->num;

temp->next = NULL;

if(list->num %2==0)

{

if(even == NULL)

{

even = temp;

}

else

{

reven->next = temp;

}

reven = temp;

}

else

{

if(odd == NULL)

{

odd = temp;

}

else

{

rodd->next = temp;

}

rodd = temp;

}

list = list->next;

}

reven->next = odd;

*head = even;

}

void create(struct node **head)

{

int c, ch;

struct node *temp,*rear;

do

{

printf("Enter number: ");

scanf("%d",&c);

temp =(struct node *)malloc(sizeof(struct node));

temp->num = c;

temp->next = NULL;

if(*head == NULL)

{

*head = temp;

}

else

{

rear->next = temp;

}

rear = temp;

printf("Do you wish to continue [1/0]: ");

scanf("%d",&ch);

}while(ch !=0);

printf("\n");

}

void display(struct node *p)

{

while(p != NULL)

{

printf("%d\t", p->num);

p = p->next;

}

printf("\n");

}

void release(struct node **head)

{

struct node *temp =*head;

*head =(*head)->next;

while((*head)!= NULL)

{

free(temp);

temp =*head;

(*head)=(*head)->next;

}

}

$ gcc evenodd.c
$ ./a.out
Enter data into the list
Enter number: 1
Do you wish to continue[1/0]: 1
Enter number: 2
Do you wish to continue[1/0]: 1
Enter number: 3
Do you wish to continue[1/0]: 1
Enter number: 4
Do you wish to continue[1/0]: 1
Enter number: 5
Do you wish to continue[1/0]: 1
Enter number: 6
Do you wish to continue[1/0]: 0
Displaying the nodes in the list:
123456
Displaying the list with even and then odd:
246135