Arrange even and odd elements of a linked list

Given collection of integer element in a linked list, Our goal is to arrange the linked list node Even after Odd elements.

 
Example 1
Linked List    :    6  4  5  10  3  7  9  2  8
After arrange  :
Linked List    :    6  5  4  3  10  7  2  9  8
[Even node -> Odd node -> Even node -> Odd node etc]

Example 2 
Linked List    :    1  2  3  4  5  6
After arrange  :
Linked List    :    2  1  4  3  6  5

In above example linked list contains same length of even and odd nodes. When Even and Odd nodes length are not same so extra nodes are added at end of resultant linked list. For example.

 
// When Odd nodes are more than Even
Example 1
Linked List :   1  1  4  2  3  1

{ 
    Even Nodes :  4  2
    Odd  Nodes :  1  1  3  1


    Combine Element  
    [4  1] 

    //Remaining
    Even Nodes :  2
    Odd  Nodes :  1  3  1

    Combine Element  
    [4  1  2  1]

    //Remaining
    Even Nodes :  
    Odd  Nodes :  3  1

    Final Element
    [4  1  2  1  3  1]
}

After arrange : 
Linked List :   4  1  2  1  3  1


// When Even nodes are more than Odd
Example 2
Linked List :   2  6  4  8  3  3  2

{
    Even Nodes :  2  6  4  8  2
    Odd  Nodes :  3  3
    
    Combine Element  
    [3  2] 
    
    //Remaining
    Even Nodes :  6  4  8  2
    Odd  Nodes :  3

    Combine Element  
    [3  2  6  3] 

    //Remaining
    Even Nodes :  4  8  2
    Odd  Nodes :  

    Final Element
    [3  2  6  3  4  8  2] 

}
After arrange : 
Linked List :   2  3  6  3  4  8  2

Here given code implementation process.



Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved