Reverse even elements in a Linked List

• Difficulty Level : Hard
• Last Updated : 09 Jun, 2021

Given a linked list, the task is to reverse the contiguous even elements and print the updated linked list.

Input: 1 -> 2 -> 3 -> 3 -> 4 -> 6 -> 8 -> 5 -> NULL
Output: 1 2 3 3 8 6 4 5
Initial list: 1 -> 2 -> 3 -> 3 -> 4 -> 6 -> 8 -> 5 -> NULL
Reversed list: 1 -> 2 -> 3 -> 3 -> 8 -> 6 -> 4 -> 5 -> NULL
Input: 11 -> 32 -> 7 -> NULL
Output: 11 32 7

Approach: Reversing the contiguous even elements will not take place when:

1. The node’s value is odd.
2. The node’s value is even but adjacent values are odd.

In rest of the cases, the continuous block of even nodes can be reversed.
Below is the implementation of the above approach:

Java

Python

# Python implementation of the approach

# Node of a linked list
class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data

# Function to create a new node
def newNode( d):

newnode = Node()
newnode.data = d
newnode.next = None
return newnode

# Recursive function to reverse the consecutive
# even nodes of the linked list

# Base case
return None

temp = None
curr = None

# Reversing nodes until curr node's value
# turn odd or Linked list is fully traversed
while (curr != None and curr.data % 2 == 0) :
temp = curr.next
curr.next = prev
prev = curr
curr = temp

# If elements were reversed then head
# pointer needs to be changed

# Recur for the remaining linked list
curr = reverse(curr, None)
return prev

# Simply iterate over the odd value nodes
else:

# Utility function to print the
# contents of the linked list

# Driver code
arr = [ 1, 2, 3, 3, 4, 6, 8, 5 ]
n = len(arr)

p = Node()

i = 0

while ( i < n ):

p = newNode(arr[i])
else:
p.next = newNode(arr[i])
p = p.next
i = i + 1;

# Printing the reversed linked list

# This code is contributed by Arnab Kundu

Javascript


Output:
1 2 3 3 8 6 4 5

Time Complexity: O(N)
Space Complexity: O(1)

My Personal Notes arrow_drop_up