Rearrange even & odd Nodes in a linked list

PROBLEM :

Given a singly linked list, rearrange it in a way that all odd position nodes are together and all even positions node are together,

Input: You have to complete the method which takes one argument: the head of the linked list. You should not read any input from stdin/console..
Note: There are multiple test cases, for each test case, this method will be called individually.

Output:
Your function should return pointer to head of the modified list.

Constraints:
1 <=T<= 50
1 <=N<= 100
1 <=value<= 1000

Example:
Input:
2
4
1 2 3 4
5
1 2 3 4 5

Output:
1 3 2 4
1 3 5 2 4
   
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* Node structure
struct Node
{
    int data;
    struct Node* next;
}; */

// Should rearrange given linked list such that all even
// positioned Nodes are before odd positioned.
// Returns new head of linked List.

Node *rearrangeEvenOdd(Node *head)
{
    Node *even,*odd,*temp ;

    if(head==NULL)
        return head ;
     
    odd=head ;
    even=odd->next ;
    temp=even ;
 
    while(1)
    {
        if(even==NULL||odd==NULL||even->next==NULL)
        {
            odd->next=temp ;
            break ;
        }
        odd->next=even->next ;
        odd=odd->next ;
     
        if(odd->next==NULL)
        {
            even->next=NULL ;
            odd->next=temp ;
            break ;
        }
        even->next=odd->next ;
        even=even->next ;
    }
    return head ;
}

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : (similar approch)
--------------------------------------------------------------------------------

/* Node structure
struct Node
{
    int data;
    struct Node* next;
}; */

// Should rearrange given linked list such that all even
// positioned Nodes are before odd positioned.
// Returns new head of linked List.
Node *rearrangeEvenOdd(Node *head)
{
    if(head==NULL||head->next==NULL)
        return head ;
       
    Node *first,*second ;
    first=head ;
    second=head->next ;
   
    Node *temp,*ptr ;
    ptr=first ;
    while(ptr->next->next!=NULL){
        temp=ptr->next ;
        ptr->next=ptr->next->next ;
        ptr=temp ;
    }
   
    temp=ptr->next ;
    temp->next=NULL ;
    ptr->next=NULL ;
   
    while(first->next!=NULL)
        first=first->next ;
       
    first->next=second ;
    return head ;
}

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

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 )