Posted on by Kalkicode
Code Single linked list

Segregate even and odd nodes in a Linked List

Suppose that given of linked list is combination of integers element. And we are need to separate this linked list nodes in the form of Even and Odd Nodes. Arrange all Even key Nodes at beginning, After that arranging Odd Key Nodes.

For example inserted the following (1,2,3,4,5,6,7,8,10) node in a sequence.

Before segregate even and odd node After segregate even and odd node

Implementation approach: Use two pointers variables, let say that is p1 and p2 , and assign those pointer value to NULL. make new pointer p3 that are used to traversal of linked list node. check that p3 node value is Even Key or not.

Even then add this element at front of p1, otherwise add this element to front of p2.(when p1 is NULL then assign first Even Node reference to p1 pointer, similarly when p2 is NULL then set first odd node reference to p2 pointer).

When p3 is NULL that means, p1 is contains the Even Value linked list nodes. And p2 is combination of Odd Value nodes. append p1 last node next pointer is to p2. And set head pointer value to p1.

Test cases: Before write an algorithm consider following test cases.

1) When linked list are empty then display valid message (like empty linked list).

2) There is possible linked list is combination of similar type of elements like All Even key or all Odd key. for example.

Case 1: (all Even key nodes)
Linked List : 1->3->5->7-9->NULL
After Segregate: 1->3->5->7-9->NULL (not modified element)

Case 2: (all Odd key nodes)
Linked List : 2->4->6->8->NULL
After Segregate:  2->4->6->8->NULL (not modified element)

In this situation are not modified the original linked list.

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