How to group even and odd nodes together in a linked list
In this article, we are going to learn how to rearrange the nodes in a singly linked list so that its odd elements come before its even elements.
Algorithm
The basic idea is to split the list into two separate lists for even elements and odd elements, and then to append the even elements to the odd elements.
Complexity analysis
The time complexity of this algorithm is O(N) where N is the number of nodes in the input linked list.
Code example
main.cpp
Node.h
#include <iostream>#include "Node.h"using namespace std;//Rearrange a linked list such that all the odd elements come before the even elementsNode * rearrange(Node * head){Node *current = head;Node *prevOdd = nullptr, *prevEven = nullptr;Node *evenHead = nullptr, *oddHead = nullptr;while(current){// add current in odd elements listif(current->data % 2 == 1){if(prevOdd)prevOdd->next = current;elseoddHead = current;prevOdd = current;}else {if(prevEven)prevEven->next = current;elseevenHead = current;prevEven = current;}current = current->next;}//prevEven->next may be nullptr or an odd node.if(evenHead)prevEven->next = nullptr;//append even elements to odd elementsif(oddHead)prevOdd->next = evenHead;elseoddHead = evenHead;return oddHead;}//arr will be used for list1 valuesint arr[] = { 1,2,4,3,5,7,8,6,9};int size = 9;
Explanation
In main.cpp, we do the following:
- Lines 11–28: We traverse a list where
currentis the current node. - Lines 13–18: We point to the last added odd node with
prevOdd. Sincecurrenthas an odd value,currentis appended to the odd list andprevOddis updated to point tocurrent. - Lines 21–25: We point to the last added even node with
prevEven. Sincecurrenthas an even value,currentis appended to the even list andprevEvenis updated to point tocurrent. - Lines 30–31: We point to the last even node with
prevEven. We also see thatprevEven->nextmay benullptror an odd node. It is updated toNULLto prevent loops. - Lines 34–37: We append even elements to odd elements where
oddHeadorevenHeadmay point to empty lists.