Odd Even Linked List

In this tutorial, I am going to discuss a programming question how to segregate even and odd nodes in a linked list or odd even linked list.

Given a singly linked list, We have to write a code to group all odd nodes together followed by the even nodes. We have to group based on node number not the value present in the node.

Try to solve this problem in O(n) time complexity and O(1) space complexity where n is the no. of nodes in a linked list.

Also, the relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on …

For example –

In the this example, Given input linked list is

1 -> 2 -> 3 -> 4 -> NULL

When we segregate even and odd nodes in a Linked List then the output is

1 -> 3 -> 2 -> 4 -> NULL

Let’s discuss how we can solve this problem. As per the problem statement we have to solve this problem in O(n) time complexity and by using constant space.

We will start with the easiest approach and finally we solve this problem in given time and space constraint.

Programming Questions on Linked List

Programming Video Tutorials

Segregate Even and Odd Nodes in a Linked List – Java Code

The easiest way to solve this problem is to create a new list. Traverse a singly linked list and than put the odd index nodes first then traverse a linked list again to put the even index nodes.

Check if a linked list is palindrome or not

Remove Nth node from the end of a linked list

Even After Odd Linked List – Java Code

In our previous approach, we have solved this problem using two traversal. Let’s think how we can solve this problem in a single traversal. We can solve this problem in single traversal by taking two list.

The idea here is to separate the linked list into two parts, even and odd list. The separation is based on index. The index is started from 1. Traverse a linked list and put odd and even nodes separately by maintaining it’s relative order. At the end we can combine both the list.

The time complexity of this approach is O(n) and it’s space complexity is also O(n).

Odd Even Linked List LeetCode Solution – Java Code

Now, let’s discuss our final approach in which we solve this problem by using constant space.

The idea here is to use two pointers (even and odd). The odd pointer points to odd nodes and even pointer points to even node. In this way, by doing pointer manipulation we can solve this problem.

Time complexity O(n).

Space Complexity O(1).

Find the intersection of two linked lists

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.