Given a singly Linked List, the task is to swap the first odd valued node from the beginning and the first even valued node from the end of the Linked List. If the list contains node values of a single parity, then no modifications are required.
Input: 4 -> 3 -> 5 -> 2 -> 3 -> NULL
Output: 4 -> 2 -> 5 -> 3 -> 3 -> NULL
4 -> 3 -> 5 -> 2 -> 3 -> NULL ===> 4 -> 2 -> 5 -> 3 -> 3 -> NULL
The first odd value in any node from the beginning is 3.
The first even value in any node from the end is 2.
After swapping the above two node values, the linked list modifies to 4 -> 2 -> 5 -> 3 -> 3 -> NULL.
Input: LL: 2 -> 6 -> 8 -> 2 -> NULL
Output: 2 -> 6 -> 8 -> 2 -> NULL
Approach: The given problem can be solved by keeping track of the first and the last occurrences of odd and even valued nodes respectively and swapping them. Follow the steps below to solve the problem:
- Initialize two variables, say firstOdd and firstEven, to store the first node having odd and even values from the beginning and the end respectively.
- Initialize two variables, say firstOdd and firstEven (initially NULL).
- Traverse the linked list and perform the following steps:
- If the value of the current node is odd and firstOdd is NULL, then update the firstOdd node to the current node.
- Otherwise, update the firstEven as the current node.
- After completing the above steps, if firstOdd and firstEven is not NULL, then swap the values at both the pointers.
- Print the modified Linked List as the resultant Linked List.
Below is the implementation of the above approach:
4 2 5 3 3
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.