Segregate even and odd nodes in a Linked List

PROBLEM :

Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the number of elements in Linked List.
The second line of each test case contains N input,elements in Linked List.

Output:

Print the all even numbers then odd numbers in the modified Linked List.

Constraints:

1 = T = 100
1 = N = 100
1 = size of elements = 1000

Example:

Input
3
7
17 15 8 9 2 4 6
4
1 3 5 7
7
8 12 10 5 4 1 6

Output
8 2 4 6 17 15 9
1 3 5 7
8 12 10 4 6 5 1
     
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<malloc.h>
typedef struct NODE
{
int data ;
struct NODE *next ;
}node ;
void create_list(node **,int) ;
void even_odd(node **) ;

int main()
 {
int t,no,i,ele ;
cin>>t ;
while(t--)
{
   node *head=NULL ;
 
   cin>>no ;
   for(i=0;i<no;i++)
   {
       cin>>ele ;
       create_list(&head,ele) ;
   }
 
   even_odd(&head) ;
 
   node *temp ;
   temp=(head) ;
   while(temp!=NULL)
   {
   cout<<temp->data<<" " ;
   temp=temp->next ;
   }
   cout<<endl ;
}
return 0;
}

void create_list(node **head,int ele)
{
node *temp,*ptr ;
temp=(node*)malloc(sizeof(node)) ;
temp->data=ele ;
temp->next=NULL ;

if((*head)==NULL)
(*head)=temp ;

else
{
ptr=(*head) ;
while(ptr->next!=NULL)
ptr=ptr->next ;
ptr->next=temp ;
}
}

void even_odd(node **head)
{
    if((*head)==NULL||(*head)->next==NULL)
        return ;
     
    node *t1,*t2,*temp,*ptr ;
   
    t1=NULL ;
    t2=NULL ;
   
    temp=(*head) ;
    while(temp!=NULL)
    {
    if((temp->data)%2==0)
    {
    t1=temp ;
    break ;
}
temp=temp->next ;
}

temp=(*head) ;
    while(temp!=NULL)
    {
    if((temp->data)%2!=0)
    {
    t2=temp ;
    break ;
}
temp=temp->next ;
}

if(t1==NULL||t2==NULL)
return ;                    

temp=(*head) ;
while(temp->next!=NULL)
temp=temp->next ;
t2=temp ;

t1=(*head) ;
while(t1->data%2!=0)
{
(*head)=t1->next ;
temp->next=t1 ;
t1->next=NULL ;
temp=temp->next ;

t1=(*head) ;
}

t1=(*head) ;
while(t1->next!=t2)
{
if(t1->next->data%2!=0)
{
ptr=t1->next ;
t1->next=ptr->next ;
temp->next=ptr ;
ptr->next=NULL ;
temp=temp->next;
}
else
t1=t1->next ;
}
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )