XOR Linked List – Insert an element at a specific position
Given a XOR linked list and two integers position and value, the task is to insert a node containing value as the positionth node of the XOR Linked List.
Input: 4<–>7<–>9<–>7, position = 3, value = 6
Inserting a node at the 3rd position with value 6 modifies the given XOR Linked List to 4<–>7<–>6<–>9<–>7.
Input: 4<–>7<–>9<–>7, position=6, value=6
Output: Invalid Position
Explanation: Since the given list consists of only 4 elements, 6th position is an invalid position in the given list.
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say ctr to keep a count of the nodes traversed in the given XOR linked list.
- Traverse the given XOR linked list. For every node of the XOR Linked List, check if the position of the current node in equal to position or not. If found to be true, then insert the node in the given XOR linked list.
- Otherwise, increment ctr by 1.
- If the entire list is traversed and positionth node was not obtained, then print “Invalid Position”.
Below is the implementation of the above approach:
20 40 10 30
Time Complexity: O(N)
Auxiliary Space: O(1)