Subtraction of the alternate nodes of Linked List

• Last Updated : 24 Jun, 2021

Given a linked list. The task is to print the difference between the first odd positioned node with the sum of all other odd positioned nodes.
Examples:

Input : 1 -> 8 -> 3 -> 10 -> 17 -> 22 -> 29 -> 42
Output : -48
Alternate nodes : 1 -> 3 -> 17 -> 29
1 – (3 + 17 + 29) = -48
Input : 10 -> 17 -> 33 -> 38 -> 73
Output : -96
Alternate nodes : 10 -> 33 -> 73
10 – (33 + 73) = -96

We have already discussed the sum of the alternative nodes of a linked list
Iterative Approach :

1. Traverse the whole linked list.
2. Set difference = 0 and count=0.
3. Subtract the data of node from difference when count is even.
4. Visit the next node.

Below is the implementation of the above approach:

Javascript



Output:

-15

Recursive Approach :

1. Initialize a static variable(say flag).
2. If flag is odd, subtract the node from difference.
3. increase head and flag by 1, and recurse for next nodes.

Below is the implementation of the above approach:

Javascript



Output:

-15

My Personal Notes arrow_drop_up