Rearrange a linked list such that all even and odd positioned nodes are together
Last Updated :
19 Jul, 2023
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together,
Examples:
Input: 1->2->3->4
Output: 1->3->2->4
Input: 10->22->30->43->56->70
Output: 10->30->56->22->43->70
The important thing in this question is to make sure that all below cases are handled
- Empty linked list
- A linked list with only one node
- A linked list with only two nodes
- A linked list with an odd number of nodes
- A linked list with an even number of nodes
The below program maintains two pointers ‘odd’ and ‘even’ for current nodes at odd and even positions respectively. We also store the first node of even linked list so that we can attach the even list at the end of odd list after all odd and even nodes are connected together in two different lists.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
Node* newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
Node *rearrangeEvenOdd(Node *head)
{
if (head == NULL)
return NULL;
Node *odd = head;
Node *even = head->next;
Node *evenFirst = even;
while (1)
{
if (!odd || !even || !(even->next))
{
odd->next = evenFirst;
break;
}
odd->next = even->next;
odd = even->next;
if (odd->next == NULL)
{
even->next = NULL;
odd->next = evenFirst;
break;
}
even->next = odd->next;
even = odd->next;
}
return head;
}
void printlist(Node * node)
{
while (node != NULL)
{
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main(void)
{
Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
cout << "Given Linked List\n";
printlist(head);
head = rearrangeEvenOdd(head);
cout << "Modified Linked List\n";
printlist(head);
return 0;
}
|
C
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
Node* newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
Node *rearrangeEvenOdd(Node *head)
{
if (head == NULL)
return NULL;
Node *odd = head;
Node *even = head->next;
Node *evenFirst = even;
while (1)
{
if (!odd || !even || !(even->next))
{
odd->next = evenFirst;
break;
}
odd->next = even->next;
odd = even->next;
if (odd->next == NULL)
{
even->next = NULL;
odd->next = evenFirst;
break;
}
even->next = odd->next;
even = odd->next;
}
return head;
}
void printlist(Node * node)
{
while (node != NULL)
{
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main(void)
{
Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
cout << "Given Linked List\n";
printlist(head);
head = rearrangeEvenOdd(head);
cout << "\nModified Linked List\n";
printlist(head);
return 0;
}
|
Java
class GfG
{
static class Node
{
int data;
Node next;
}
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
static Node rearrangeEvenOdd(Node head)
{
if (head == null)
return null;
Node odd = head;
Node even = head.next;
Node evenFirst = even;
while (1 == 1)
{
if (odd == null || even == null ||
(even.next) == null)
{
odd.next = evenFirst;
break;
}
odd.next = even.next;
odd = even.next;
if (odd.next == null)
{
even.next = null;
odd.next = evenFirst;
break;
}
even.next = odd.next;
even = odd.next;
}
return head;
}
static void printlist(Node node)
{
while (node != null)
{
System.out.print(node.data + "->");
node = node.next;
}
System.out.println("NULL") ;
}
public static void main(String[] args)
{
Node head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(5);
System.out.println("Given Linked List");
printlist(head);
head = rearrangeEvenOdd(head);
System.out.println("Modified Linked List");
printlist(head);
}
}
|
Python3
class Node:
def __init__(self, d):
self.data = d
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def newNode(self, key):
temp = Node(key)
self.next = None
return temp
def rearrangeEvenOdd(self, head):
if (self.head == None):
return None
odd = self.head
even = self.head.next
evenFirst = even
while (1 == 1):
if (odd == None or even == None or
(even.next) == None):
odd.next = evenFirst
break
odd.next = even.next
odd = even.next
if (odd.next == None):
even.next = None
odd.next = evenFirst
break
even.next = odd.next
even = odd.next
return head
def printlist(self, node):
while (node != None):
print(node.data, end = "")
print("->", end = "")
node = node.next
print ("NULL")
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
ll = LinkedList()
ll.push(5)
ll.push(4)
ll.push(3)
ll.push(2)
ll.push(1)
print ("Given Linked List")
ll.printlist(ll.head)
start = ll.rearrangeEvenOdd(ll.head)
print ("\nModified Linked List")
ll.printlist(start)
|
C#
using System;
class GfG
{
class Node
{
public int data;
public Node next;
}
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
static Node rearrangeEvenOdd(Node head)
{
if (head == null)
return null;
Node odd = head;
Node even = head.next;
Node evenFirst = even;
while (1 == 1)
{
if (odd == null || even == null ||
(even.next) == null)
{
odd.next = evenFirst;
break;
}
odd.next = even.next;
odd = even.next;
if (odd.next == null)
{
even.next = null;
odd.next = evenFirst;
break;
}
even.next = odd.next;
even = odd.next;
}
return head;
}
static void printlist(Node node)
{
while (node != null)
{
Console.Write(node.data + "->");
node = node.next;
}
Console.WriteLine("NULL") ;
}
public static void Main()
{
Node head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(5);
Console.WriteLine("Given Linked List");
printlist(head);
head = rearrangeEvenOdd(head);
Console.WriteLine("Modified Linked List");
printlist(head);
}
}
|
Javascript
<script>
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
function newNode(key) {
var temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
function rearrangeEvenOdd(head) {
if (head == null)
return null;
var odd = head;
var even = head.next;
var evenFirst = even;
while (1 == 1) {
if (odd == null || even == null ||
(even.next) == null)
{
odd.next = evenFirst;
break;
}
odd.next = even.next;
odd = even.next;
if (odd.next == null) {
even.next = null;
odd.next = evenFirst;
break;
}
even.next = odd.next;
even = odd.next;
}
return head;
}
function printlist(node) {
while (node != null) {
document.write(node.data + "->");
node = node.next;
}
document.write("NULL<br/>");
}
var head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(5);
document.write("Given Linked List<br/>");
printlist(head);
head = rearrangeEvenOdd(head);
document.write("Modified Linked List<br/>");
printlist(head);
</script>
|
Output
Given Linked List
1->2->3->4->5->NULL
Modified Linked List
1->3->5->2->4->NULL
Time complexity: O(n) since using a loop to traverse the list, where n is the size of the linked list
Auxiliary Space: O(1)
Please see here another code contributed by Gautam Singh.
A More Clean Concise Code:
Approach:
- Have 4 Pointers
- OddStart, OddEnd, EvenStart, EvenEnd.
- As the names are made, the pointers also point in such a way.
- Atlast simply connect the end of Odd List to Start of Even List.
- Mark the Even List End as NULL.
C++
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* next;
};
Node* newNode(int key)
{
Node *temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
void rearrangeEvenOdd(Node *head)
{
if(head==NULL || head->next == NULL){
return;
}
Node* temp = head;
Node* oddStart = NULL;
Node* oddEnd = NULL;
Node* evenStart = NULL;
Node* evenEnd = NULL;
int i = 1;
while(temp != NULL){
if(i%2 ==0){
if(evenStart == NULL){
evenStart = temp;
}
else{
evenEnd->next = temp;
}
evenEnd = temp;
}
else{
if(oddStart == NULL){
oddStart = temp;
}
else{
oddEnd->next = temp;
}
oddEnd = temp;
}
temp = temp->next;
i++;
}
oddEnd->next = evenStart;
evenEnd->next = NULL;
head = oddStart;
}
void printlist(Node * node)
{
while (node != NULL)
{
cout << node->data << "->";
node = node->next;
}
cout << "NULL" << endl;
}
int main(void)
{
Node *head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head->next->next->next = newNode(4);
head->next->next->next->next = newNode(5);
head->next->next->next->next->next = newNode(6);
cout << "Given Linked List\n";
printlist(head);
rearrangeEvenOdd(head);
cout << "\nModified Linked List\n";
printlist(head);
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
LinkedList() { this.head = null; }
Node newNode(int key)
{
Node temp = new Node(key);
temp.next = null;
return temp;
}
Node rearrangeEvenOdd(Node head)
{
if (head == null || head.next == null) {
return null;
}
Node temp = head;
Node oddStart = null;
Node oddEnd = null;
Node evenStart = null;
Node evenEnd = null;
int i = 1;
while (temp != null) {
if (i % 2 == 0) {
if (evenStart == null) {
evenStart = temp;
}
else {
evenEnd.next = temp;
}
evenEnd = temp;
}
else {
if (oddStart == null) {
oddStart = temp;
}
else {
oddEnd.next = temp;
}
oddEnd = temp;
}
temp = temp.next;
i = i + 1;
}
oddEnd.next = evenStart;
evenEnd.next = null;
return oddStart;
}
void printlist(Node node)
{
while (node != null) {
System.out.print(node.data + "->");
node = node.next;
}
System.out.println("NULL");
}
void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
}
class Main {
public static void main(String[] args)
{
LinkedList ll = new LinkedList();
ll.push(6);
ll.push(5);
ll.push(4);
ll.push(3);
ll.push(2);
ll.push(1);
System.out.println("Given Linked List");
ll.printlist(ll.head);
Node start = ll.rearrangeEvenOdd(ll.head);
System.out.println("\nModified Linked List");
ll.printlist(start);
}
}
|
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def newNode(self, key):
temp = Node(key)
self.next = None
return temp
def rearrangeEvenOdd(self, head):
if (self.head == None or self.head.next == None):
return None
temp = self.head
oddStart = None
oddEnd = None
evenStart = None
evenEnd = None
i = 1
while (temp is not None):
if(i % 2 == 0):
if evenStart is None :
evenStart = temp
else:
evenEnd.next = temp
evenEnd = temp
else:
if oddStart is None :
oddStart = temp
else:
oddEnd.next = temp
oddEnd = temp
temp = temp.next
i = i+1
oddEnd.next = evenStart
evenEnd.next = None
return oddStart
def printlist(self, node):
while (node != None):
print(node.data, end="")
print("->", end="")
node = node.next
print("NULL")
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
ll = LinkedList()
ll.push(6)
ll.push(5)
ll.push(4)
ll.push(3)
ll.push(2)
ll.push(1)
print("Given Linked List")
ll.printlist(ll.head)
start = ll.rearrangeEvenOdd(ll.head)
print("\nModified Linked List")
ll.printlist(start)
|
C#
using System;
class GfG{
class Node{
public int data;
public Node next;
}
static Node newNode(int key){
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
static Node rearrangeEvenOdd(Node head){
if(head == null || head.next == null) return null;
Node temp = head;
Node oddStart = null;
Node oddEnd = null;
Node evenStart = null;
Node evenEnd = null;
int i = 1;
while(temp != null){
if(i%2 == 0){
if(evenStart == null) evenStart = temp;
else evenEnd.next = temp;
evenEnd = temp;
}else{
if(oddStart == null) oddStart = temp;
else oddEnd.next = temp;
oddEnd = temp;
}
temp = temp.next;
i++;
}
oddEnd.next = evenStart;
evenEnd.next = null;
return oddStart;
}
static void printlist(Node node)
{
while (node != null)
{
Console.Write(node.data + "->");
node = node.next;
}
Console.WriteLine("NULL") ;
}
public static void Main()
{
Node head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(5);
head.next.next.next.next.next = newNode(6);
Console.WriteLine("Given Linked List");
printlist(head);
head = rearrangeEvenOdd(head);
Console.WriteLine("\nModified Linked List");
printlist(head);
}
}
|
Javascript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
newNode(key) {
temp = new Node(key);
this.next = null;
return temp;
}
rearrangeEvenOdd(head) {
if (this.head == null || this.head.next == null) {
return null;
}
var temp = this.head;
var oddStart = null;
var oddEnd = null;
var evenStart = null;
var evenEnd = null;
var i = 1;
while (temp != null) {
if (i % 2 == 0) {
if (evenStart == null) {
evenStart = temp;
} else {
evenEnd.next = temp;
}
evenEnd = temp;
} else {
if (oddStart == null) {
oddStart = temp;
} else {
oddEnd.next = temp;
}
oddEnd = temp;
}
temp = temp.next;
i = i + 1;
}
oddEnd.next = evenStart;
evenEnd.next = null;
return oddStart;
}
printlist(node) {
while (node != null) {
process.stdout.write(node.data+"->");
node = node.next;
}
console.log("NULL");
}
push(new_data) {
var new_node = new Node(new_data);
new_node.next = this.head;
this.head = new_node;
}
}
ll = new LinkedList();
ll.push(6);
ll.push(5);
ll.push(4);
ll.push(3);
ll.push(2);
ll.push(1);
console.log("Given Linked List");
ll.printlist(ll.head);
start = ll.rearrangeEvenOdd(ll.head);
console.log("\nModified Linked List");
ll.printlist(start);
|
Output
Given Linked List
1->2->3->4->5->6->NULL
Modified Linked List
1->3->5->2->4->6->NULL
Time complexity: O(n) since using a loop to traverse the list, where n is the size of the linked list
Auxiliary Space: O(1) As only few pointers.
Approach:
To rearrange the linked list in such a way that all odd-positioned nodes are together and all even-positioned nodes are together, we can follow the following steps:
- We will create two separate linked lists, one for odd-positioned nodes and the other for even-positioned nodes.
- We will traverse the original linked list, and for each node, we will check its position.
- If the position is odd, we will add that node to the odd-positioned linked list, and if the position is even, we will add that node to the even-positioned linked list.
- Once we have added all the nodes to their respective linked lists, we will merge these two linked lists to form the final rearranged linked list.
Steps:
- Initialize three pointers, namely odd_head, even_head, and curr.
- Traverse the original linked list using the curr pointer.
- For each node, check its position using a counter variable.
- If the position is odd, add that node to the end of the odd-positioned linked list and update the odd_head pointer if necessary.
- If the position is even, add that node to the end of the even-positioned linked list and update the even_head pointer if necessary.
- Once we have traversed the entire original linked list, merge the odd_positioned linked list and the even_positioned linked list to form the final rearranged linked list.
- Return the rearranged linked list.
C++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* rearrange_linked_list(ListNode* head) {
ListNode* odd_head = new ListNode(0);
ListNode* odd = odd_head;
ListNode* even_head = new ListNode(0);
ListNode* even = even_head;
ListNode* curr = head;
int counter = 1;
while (curr) {
if (counter % 2 == 1) {
odd->next = curr;
odd = odd->next;
}
else {
even->next = curr;
even = even->next;
}
curr = curr->next;
counter++;
}
odd->next = even_head->next;
even->next = NULL;
return odd_head->next;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
ListNode* new_head = rearrange_linked_list(head);
while (new_head) {
cout << new_head->val << "->";
new_head = new_head->next;
}
return 0;
}
|
Java
class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
ListNode(int val) {
this(val, null);
}
}
class Solution {
public ListNode rearrangeLinkedList(ListNode head) {
ListNode oddHead = new ListNode(0), odd = oddHead;
ListNode evenHead = new ListNode(0), even = evenHead;
ListNode curr = head;
int counter = 1;
while (curr != null) {
if (counter % 2 == 1) {
odd.next = curr;
odd = odd.next;
} else {
even.next = curr;
even = even.next;
}
curr = curr.next;
counter++;
}
odd.next = evenHead.next;
even.next = null;
return oddHead.next;
}
}
public class Main {
public static void main(String[] args) {
ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
Solution solution = new Solution();
ListNode newHead = solution.rearrangeLinkedList(head);
while (newHead != null) {
System.out.print(newHead.val + "->");
newHead = newHead.next;
}
}
}
|
Python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def rearrange_linked_list(head: ListNode) -> ListNode:
odd_head = odd = ListNode(0)
even_head = even = ListNode(0)
curr = head
counter = 1
while curr:
if counter % 2 == 1:
odd.next = curr
odd = odd.next
else:
even.next = curr
even = even.next
curr = curr.next
counter += 1
odd.next = even_head.next
even.next = None
return odd_head.next
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
new_head = rearrange_linked_list(head)
while new_head:
print(new_head.val, end="->")
new_head = new_head.next
|
C#
using System;
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
public class Solution
{
public ListNode RearrangeLinkedList(ListNode head)
{
ListNode oddHead = new ListNode(0);
ListNode odd = oddHead;
ListNode evenHead = new ListNode(0);
ListNode even = evenHead;
ListNode curr = head;
int counter = 1;
while (curr != null)
{
if (counter % 2 == 1)
{
odd.next = curr;
odd = odd.next;
}
else
{
even.next = curr;
even = even.next;
}
curr = curr.next;
counter++;
}
odd.next = evenHead.next;
even.next = null;
return oddHead.next;
}
}
public class Program
{
public static void Main(string[] args)
{
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
Solution solution = new Solution();
ListNode newHead = solution.RearrangeLinkedList(head);
while (newHead != null)
{
Console.Write(newHead.val + "->");
newHead = newHead.next;
}
}
}
|
Javascript
class ListNode {
constructor(val = 0, next = null) {
this.val = val;
this.next = next;
}
}
function rearrangeLinkedList(head) {
let oddHead = odd = new ListNode(0);
let evenHead = even = new ListNode(0);
let curr = head;
let counter = 1;
while (curr) {
if (counter % 2 === 1) {
odd.next = curr;
odd = odd.next;
} else {
even.next = curr;
even = even.next;
}
curr = curr.next;
counter++;
}
odd.next = evenHead.next;
even.next = null;
return oddHead.next;
}
let head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
let newHead = rearrangeLinkedList(head);
while (newHead) {
console.log(newHead.val + "->");
newHead = newHead.next;
}
|
Time complexity: The time complexity of the above algorithm is O(n), where n is the number of nodes in the linked list.
Auxiliary space: The auxiliary space used by the above algorithm is O(1)
Similar Reads
Rearrange a linked list such that all even and odd positioned nodes are together
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4Output: 1->3->2->4Input: 10->22->30->43->56->70Output: 10->30->56->22->43->70The important thing in this
15+ min read
Javascript Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4Output: 1->3->2->4Input: 10->22->30->43->56->70Output: 10->30->56->22->43->70The important thing in this
3 min read
Reverse the order of all nodes at even position in given Linked List
Given a linked list A[] of N integers, the task is to reverse the order of all integers at an even position. Examples: Input: A[] = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULLOutput: 1 6 3 4 5 2Explanation: Nodes at even position in the given linked list are 2, 4 and 6. So, after reversing
10 min read
Segregate even and odd nodes in a Linked List
Given a Linked List of integers, The task is to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, preserve the order of even and odd numbers. Examples: Input: 17->15->8->12->10->5->4->1->7->6->NULLOutp
15+ min read
Rearrange given Array such that each element raised to its index is odd
Given an array arr of length N, the task is to rearrange the elements of given array such that for each element, its bitwise XOR with its index is an odd value. If no rearrangement is possible return -1. Example: Input: arr[] = {1 2 4 3 5}Output: 1 2 3 4 5Explanation: In the above array:for 1st elem
13 min read
Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> NULL Output : 1 -> 3 -
11 min read
Merge odd and even positioned nodes of two Linked Lists alternately
Given two linked lists L1 and L2, the task is to print a new list obtained by merging odd position nodes of L1 with the even positioned nodes of L2 alternately. Examples: Input: L1 = 8->5->3->2->10->NULL, L2 = 11->13->1->6->9->NULLOutput: 8->13->3->6->10-
15 min read
Segregate even and odd nodes in a Linked List using Deque
Given a Linked List of integers. The task is to write a program to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. It is not needed to keep the order of even and odd nodes the same as that of the original list, the task is just to rear
10 min read
Rearrange array such that all even-indexed elements in the Array is even
Given an array arr[], the task is to check if it is possible to rearrange the array in such a way that every even index(1-based indexing) contains an even number. If such a rearrangement is not possible, print "No". Otherwise, print "Yes" and print a possible arrangement Examples: Input: arr[] = {2,
6 min read
Sum and Product of all even digit sum Nodes of a Singly Linked List
Given a singly linked list containing N nodes, the task is to find the sum and product of all the nodes from the list whose data value has an even digit sum. Examples: Input: 15 -> 16 -> 8 -> 6 -> 13 Output: Sum = 42 Product = 9360 Explanation: The sum of all digit of number in linked li
15+ min read