GeeksforGeeks App
Open App
Browser
Continue

# Traverse Linked List from middle to left-right order using recursion

Given a Linked List. The task is to traverse the Linked List from middle to left-right order using recursion.
For Example:

If the given Linked List is: 2 -> 5 -> 8 -> 3 -> 7 -> 9 -> 12 -> NULL
The Middle to left-right order is : 3, 8, 7, 5, 9, 2, 12

Explanation: Middle of the given linked list is ‘3’ so, we start traversing from middle by printing 3 then left and right of 3, so we print 8, 7 then print left of 8 and right of 7, so we print 5, 9 then print left of 5 and right of 9, so we print 2, 12.
Note: If number of node are even in a Linked List then print left right only. For this linked list( contains even number of nodes ) 2 -> 5 -> 8 -> 7 -> 9 -> 12 -> NULL.
The output should be 8, 7, 5, 9, 2, 12.
Examples:

Input: 20 -> 15 -> 23 -> 13 -> 19 -> 32 -> 16 -> 41 -> 11 -> NULL
Output: 19, 13, 32, 23, 16, 15, 41, 20, 11.
Input: 12 -> 25 -> 51 -> 16 -> 9 -> 90 -> 7 -> 2 -> NULL
Output: 16, 9, 51, 90, 25, 7, 12, 2.

Approach:
First, calculate the size of the linked list:

• If size is odd:
-> Then go to the (n+1)/2 -th node using recursion.
• If size is even:
-> Then go to the n/2 -th node using recursion.
• Now print node data and return next node address, do this procedure unless function call stack empty.

Below is the implementation of the above approach:

## Javascript



Output:

Created Linked list is:  6-> 4-> 8-> 7-> 9-> 11-> 2
Output : 7 , 8 , 9 , 4 , 11 , 6 , 2

Time complexity: O(N) where N is the size of the given linked list

Auxiliary space: O(N) for call stack

My Personal Notes arrow_drop_up