I want a C program to rearrange a linked list so that nodes with even numbers as their information come first. Input:The input consists of the information in each node of the linked list. Output:The program displays the information in the linked list after the links are rearranged. Sample Input:Enter the information in the linked list (Enter -1 to exit): 321020478-1Sample Output:After links are rearrangedInformation in the linked list:21020483

Questions by souji1425

Showing Answers 1 - 3 of 3 Answers

baseersd

  • Jan 21st, 2008
 

#include<stdio.h>
typedef struct _node NODE;

struct _node
{
 int num;
 NODE *next;       
};

NODE* New_Node(NODE *Head,int num)
{
 NODE *temp,*Curr;
 if(Head == NULL)
 {
         Head = (NODE*)malloc(sizeof(NODE));
         Head->next = NULL;
         Head->num = num;
         return Head;        
 }      
 Curr = Head;
 while(Curr->next != NULL)
 {
   Curr = Curr->next;
 }
 temp = (NODE*)malloc(sizeof(NODE));
     if(temp == NULL){
     printf("Cannot create a new noden");
     return Head;
     }
 Curr->next = temp;
 temp->num = num;    
 temp->next = NULL;
       

 return Head;
}

void Print_Nodes(NODE *Head)
{
 NODE *temp;
 temp = Head;
 while(temp != NULL)
 {
            printf("n%d",temp->num);
            temp = temp->next;           
 }    
}

void Rearrange(NODE *Head)
{
 NODE *Even = NULL;
 NODE *Odd = NULL;
 NODE *temp;
 
 temp = Head;
 while(temp != NULL)
 {
                  if(temp->num %2 == 0)                  
                    Even = New_Node(Even,temp->num);                     
                  else
                    Odd = New_Node(Odd,temp->num);  
   temp = temp->next;
 }
 free(Head);
 Head = Even;
 while(Even->next != NULL)
 Even = Even->next;
 
 Even->next = Odd;
 
 printf("nAfter rearrange the list is ::n");
 Print_Nodes(Head);
      
}
int main()
{
    int num=0;
    NODE *Head = NULL;
     printf("nEnter the information in the linked list (Enter -1 to exit):");
     scanf("%d",&num);
  while(num != -1)
  {
             Head = New_Node(Head,num);
             printf("nEnter the information in the linked list (Enter -1 to exit):");
             scanf("%d",&num);
  }   
  Print_Nodes(Head) ;
  Rearrange(Head);
 getch();    
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions