Program to separate Even and Odd numbers in a linked list


struct node
{
  int data;
  struct node *next;
};
 
void separateEvenOdd(struct node **head_ref)
{
  struct node *end = *head_ref;
 
  struct node *prev = NULL;
  struct node *curr = *head_ref;
 

  while(end->next != NULL)
       end = end->next;
 
  struct node *new_end = end;
 
  /* Take all odd nodes before the first even node
     and move then after end */

 while(curr->data %2 != 0 && curr != end)
  {
    new_end->next = curr;
    curr = curr->next;
    new_end->next->next = NULL;
    new_end = new_end->next;
  }  
 
 
  /* Do following steps only if there is any even node */
 
if (curr->data%2 == 0)
  {
 
    *head_ref = curr;    
 
    /* now current points to the first even node */
 
 while(curr != end)
    {
      if ( (curr->data)%2 == 0 )
      {
         prev = curr;
         curr = curr->next;
      }
      else
      {
       
         prev->next = curr->next;
 
         curr->next = NULL;
 
         new_end->next = curr;
 
         new_end = curr;
 
         curr = prev->next;
      }
    }
  }
 
  else
    prev = curr;
 
  /* If the end of the original list is odd then move this node to
    end to maintain same order of odd numbers in modified list */
 
if((end->data)%2 != 0)
  {
      prev->next = end->next;
      end->next = NULL;
      new_end->next = end;
  }
  return;
}
 

Comments

Popular posts from this blog

Tricky Questions or Puzzles in C

Program to uncompress a string ie a2b3c4 to aabbbcccc

Programs and Puzzles in technical interviews i faced