Open In App

XOR Linked List – Insert an element at a specific position

Last Updated : 09 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples:

Input: 4<–>7<–>9<–>7, position = 3, value = 6 
Output: 4<–>7<–>6<–>9<–>7
Explanation: 
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:

C++




// C++ program to implement
// the above approach
 
#include<bits/stdc++.h>
using namespace std;
 
// Structure of a node
// in XOR linked list
struct Node {
 
    // Stores data value
    // of a node
    int data;
 
    // Stores XOR of previous
    // pointer and next pointer
    struct Node* nxp;
};
 
// Function to find the XOR of two nodes
struct Node* XOR(struct Node* a,
                 struct Node* b)
{
    return (struct Node*)((uintptr_t)(a)^ (uintptr_t)(b));
}
 
// Function to insert a node with
// given value at given position
struct Node* insert(struct Node** head,
                    int value, int position)
{
    // If XOR linked list is empty
    if (*head == NULL) {
 
        // If given position
        // is equal to 1
        if (position == 1) {
 
            // Initialize a new Node
            struct Node* node
                = new Node();
 
            // Stores data value in
            // the node
            node->data = value;
 
            // Stores XOR of previous
            // and next pointer
            node->nxp = XOR(NULL, NULL);
 
            // Update pointer of head node
            *head = node;
        }
 
        // If required position was not found
        else {
            cout << "Invalid Position\n";
        }
    }
 
    // If the XOR linked list
    // is not empty
    else {
 
        // Stores position of a node
        // in the XOR linked list
        int Pos = 1;
 
        // Stores the address
        // of current node
        struct Node* curr = *head;
 
        // Stores the address
        // of previous node
        struct Node* prev = NULL;
 
        // Stores the XOR of next
        // node and previous node
        struct Node* next
            = XOR(prev, curr->nxp);
 
        // Traverse the XOR linked list
        while (next != NULL && Pos < position - 1) {
 
            // Update prev
            prev = curr;
 
            // Update curr
            curr = next;
 
            // Update next
            next = XOR(prev, curr->nxp);
 
            // Update Pos
            Pos++;
        }
 
        // If the position of the current
        // node is equal to the given position
        if (Pos == position - 1) {
 
            // Initialize a new Node
            struct Node* node
                = new Node();
 
            // Stores pointer to previous Node
            // as (prev ^ next ^ next) = prev
            struct Node* temp
                = XOR(curr->nxp, next);
 
            // Stores XOR of prev and new node
            curr->nxp = XOR(temp, node);
 
            // Connecting new node with next
            if (next != NULL) {
 
                // Update pointer of next
                next->nxp = XOR(node,
                                XOR(next->nxp, curr));
            }
 
            // Connect node with curr and
            // next curr<--node-->next
            node->nxp = XOR(curr, next);
            node->data = value;
        }
 
        // Insertion node at beginning
        else if (position == 1) {
 
            // Initialize a new Node
            struct Node* node
                = new Node();
 
            // Update curr node address
            curr->nxp = XOR(node,
                            XOR(NULL, curr->nxp));
 
            // Update new node address
            node->nxp = XOR(NULL, curr);
 
            // Update head
            *head = node;
 
            // Update data value of
            // current node
            node->data = value;
        }
        else {
            cout << "Invalid Position\n";
        }
    }
    return *head;
}
 
// Function to print elements of
// the XOR Linked List
void printList(struct Node** head)
{
    // Stores XOR pointer
    // in current node
    struct Node* curr = *head;
 
    // Stores XOR pointer of
    // in previous Node
    struct Node* prev = NULL;
 
    // Stores XOR pointer of
    // in next node
    struct Node* next;
 
    // Traverse XOR linked list
    while (curr != NULL) {
 
        // Print current node
       cout << curr->data << " ";
 
        // Forward traversal
        next = XOR(prev, curr->nxp);
 
        // Update prev
        prev = curr;
 
        // Update curr
        curr = next;
    }
}
 
// Driver Code
int main()
{
    /* Create following XOR Linked List
    head-->20<-->40<-->10<-->30 */
    struct Node* head = NULL;
    insert(&head, 10, 1);
    insert(&head, 20, 1);
    insert(&head, 30, 3);
    insert(&head, 40, 2);
 
    // Print the new list
    printList(&head);
 
    return 0;
}


C




// C++ program to implement
// the above approach
 
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
 
// Structure of a node
// in XOR linked list
struct Node {
 
    // Stores data value
    // of a node
    int data;
 
    // Stores XOR of previous
    // pointer and next pointer
    struct Node* nxp;
};
 
// Function to find the XOR of two nodes
struct Node* XOR(struct Node* a,
                 struct Node* b)
{
    return (struct Node*)((uintptr_t)(a)
                          ^ (uintptr_t)(b));
}
 
// Function to insert a node with
// given value at given position
struct Node* insert(struct Node** head,
                    int value, int position)
{
    // If XOR linked list is empty
    if (*head == NULL) {
 
        // If given position
        // is equal to 1
        if (position == 1) {
 
            // Initialize a new Node
            struct Node* node
                = (struct Node*)malloc(
                    sizeof(struct Node));
 
            // Stores data value in
            // the node
            node->data = value;
 
            // Stores XOR of previous
            // and next pointer
            node->nxp = XOR(NULL, NULL);
 
            // Update pointer of head node
            *head = node;
        }
 
        // If required position was not found
        else {
            printf("Invalid Position\n");
        }
    }
 
    // If the XOR linked list
    // is not empty
    else {
 
        // Stores position of a node
        // in the XOR linked list
        int Pos = 1;
 
        // Stores the address
        // of current node
        struct Node* curr = *head;
 
        // Stores the address
        // of previous node
        struct Node* prev = NULL;
 
        // Stores the XOR of next
        // node and previous node
        struct Node* next
            = XOR(prev, curr->nxp);
 
        // Traverse the XOR linked list
        while (next != NULL && Pos < position - 1) {
 
            // Update prev
            prev = curr;
 
            // Update curr
            curr = next;
 
            // Update next
            next = XOR(prev, curr->nxp);
 
            // Update Pos
            Pos++;
        }
 
        // If the position of the current
        // node is equal to the given position
        if (Pos == position - 1) {
 
            // Initialize a new Node
            struct Node* node
                = (struct Node*)malloc(
                    sizeof(struct Node));
 
            // Stores pointer to previous Node
            // as (prev ^ next ^ next) = prev
            struct Node* temp
                = XOR(curr->nxp, next);
 
            // Stores XOR of prev and new node
            curr->nxp = XOR(temp, node);
 
            // Connecting new node with next
            if (next != NULL) {
 
                // Update pointer of next
                next->nxp = XOR(node,
                                XOR(next->nxp, curr));
            }
 
            // Connect node with curr and
            // next curr<--node-->next
            node->nxp = XOR(curr, next);
            node->data = value;
        }
 
        // Insertion node at beginning
        else if (position == 1) {
 
            // Initialize a new Node
            struct Node* node
                = (struct Node*)malloc(
                    sizeof(struct Node));
 
            // Update curr node address
            curr->nxp = XOR(node,
                            XOR(NULL, curr->nxp));
 
            // Update new node address
            node->nxp = XOR(NULL, curr);
 
            // Update head
            *head = node;
 
            // Update data value of
            // current node
            node->data = value;
        }
        else {
            printf("Invalid Position\n");
        }
    }
    return *head;
}
 
// Function to print elements of
// the XOR Linked List
void printList(struct Node** head)
{
    // Stores XOR pointer
    // in current node
    struct Node* curr = *head;
 
    // Stores XOR pointer of
    // in previous Node
    struct Node* prev = NULL;
 
    // Stores XOR pointer of
    // in next node
    struct Node* next;
 
    // Traverse XOR linked list
    while (curr != NULL) {
 
        // Print current node
        printf("%d ", curr->data);
 
        // Forward traversal
        next = XOR(prev, curr->nxp);
 
        // Update prev
        prev = curr;
 
        // Update curr
        curr = next;
    }
}
 
// Driver Code
int main()
{
    /* Create following XOR Linked List
    head-->20<-->40<-->10<-->30 */
    struct Node* head = NULL;
    insert(&head, 10, 1);
    insert(&head, 20, 1);
    insert(&head, 30, 3);
    insert(&head, 40, 2);
 
    // Print the new list
    printList(&head);
 
    return (0);
}


Java




import java.util.HashMap;
 
class Node {
    int data;
    int link;
 
    Node(int data) {
        this.data = data;
        this.link = 0;
    }
}
 
class XorLinkedList {
    Node head;
    HashMap<Integer, Node> nodes;
 
    XorLinkedList() {
        head = null;
        nodes = new HashMap<>();
    }
 
    // Method to perform XOR operation on node pointers
    private int XOR(int a, int b, int c) {
        return a ^ b ^ c;
    }
 
    // Method to traverse linked list
    void forwardTraversal() {
        if (head == null) {
            System.out.println("Empty");
        } else {
            int prevId = 0;
            Node current = head;
            System.out.print(current.data + " ");
            int nextId = 1;
 
            while (nextId != 0) {
                nextId = XOR(prevId, current.link, 0);
                if (nextId != 0) {
                    prevId = System.identityHashCode(current);
                    current = typeCast(nextId);
                    System.out.print(current.data + " ");
                }
            }
        }
    }
 
    // Method to insert a node at a given position
    void insertAtPosition(int key, int position) {
        if (position < 1) {
            System.out.println("Can't insert");
        } else if (position == 1) {
            Node newNode = new Node(key);
 
            if (head == null) {
                head = newNode;
            } else {
                head.link = XOR(System.identityHashCode(newNode), head.link, 0);
                newNode.link = System.identityHashCode(head);
                head = newNode;
            }
 
            nodes.put(System.identityHashCode(newNode), newNode);
        } else {
            if (head == null) {
                System.out.println("Out of range");
            } else {
                Node newNode = new Node(key);
                Node current = head;
                int currentId = System.identityHashCode(current);
                int i = 1;
                int prevId = 0;
                int nextId = 1;
 
                while (nextId != 0 && i < position - 1) {
                    nextId = XOR(prevId, current.link, 0);
                    prevId = System.identityHashCode(current);
 
                    if (nextId != 0) {
                        current = typeCast(nextId);
                        currentId = System.identityHashCode(current);
                        i++;
                    } else {
                        break;
                    }
                }
 
                if (i == position - 1) {
                    nextId = XOR(prevId, current.link, 0);
                    current.link = XOR(nextId, current.link, System.identityHashCode(newNode));
 
                    if (nextId != 0) {
                        Node nxt = typeCast(nextId);
                        nxt.link = XOR(System.identityHashCode(newNode), nxt.link, System.identityHashCode(current));
                        newNode.link = XOR(System.identityHashCode(current), System.identityHashCode(nxt), 0);
                    } else {
                        newNode.link = System.identityHashCode(current);
                    }
 
                    nodes.put(System.identityHashCode(newNode), newNode);
                } else {
                    System.out.println("Out of range");
                }
            }
        }
    }
 
    // Generic method to cast int to Node
    private Node typeCast(int ptr) {
        return nodes.get(ptr);
    }
}
 
public class Main {
    public static void main(String[] args) {
        XorLinkedList obj = new XorLinkedList();
        obj.insertAtPosition(10, 1);
        obj.insertAtPosition(20, 1);
        obj.insertAtPosition(30, 3);
        obj.insertAtPosition(40, 2);
        obj.forwardTraversal();
    }
}


C#




// C# program for the above approach
using System;
 
public class XorLinkedList {
    public Node head;
 
    // Structure of a node in XOR linked list
    public class Node {
        // Stores data value of a node
        public int data;
 
        // Stores XOR of previous pointer and next pointer
        public Node nxp;
 
        // Constructor to initialize node
        public Node(int value)
        {
            this.data = value;
            this.nxp = null;
        }
    }
 
    public XorLinkedList() { head = null; }
 
    // Function to insert a node with given value at given
    // position
    public Node Insert(int value, int position)
    {
        // If given position is equal to 1
        if (position == 1) {
            // Initialize a new Node
            Node node = new Node(value);
 
            // Update new node's next
            node.nxp = head;
 
            // make node as head
            head = node;
        }
 
        // If XOR linked list is empty
        else if (head == null && position > 1) {
            // If required position was not found
            Console.WriteLine("Invalid Position");
            return head;
        }
 
        // If the XOR linked list is not empty and position
        // is not 1
        else {
            // find current length
            int len = Length();
 
            // if position is out of range
            if (len < position - 1) {
                Console.WriteLine("Invalid Position");
                return head;
            }
 
            // Stores the address of previous node
            Node prev = null;
 
            // Stores the address of current node
            Node curr = head;
 
            // Traverse the XOR linked list until specific
            // position reached
            while (curr != null && position > 1) {
                // Update prev
                prev = curr;
 
                // Update curr
                curr = curr.nxp;
 
                // Update Position
                position -= 1;
            }
 
            // If the position of the current node is equal
            // to the given position
            if (position == 1) {
                // Initialize a new Node
                Node node = new Node(value);
 
                if (prev != null) {
                    // update prev
                    prev.nxp = node;
                }
 
                // update nde node's next
                node.nxp = curr;
            }
            else {
                Console.WriteLine("Invalid Position");
            }
        }
        return head;
    }
 
    // Function to print elements of the XOR Linked List
    public void PrintList()
    {
        // Stores XOR pointer in current node
        Node curr = head;
 
        // Traverse XOR linked list
        while (curr != null) {
            // Print current node
            Console.Write(curr.data + " ");
 
            // Update curr
            curr = curr.nxp;
        }
    }
 
    // Method to get length of linked list
    public int Length()
    {
        int count = 0;
        Node nextId = head;
        while (nextId != null) {
            nextId = nextId.nxp;
            count++;
        }
        return count;
    }
 
    // Driver Code
    public static void Main()
    {
        /* Create following XOR Linked List
        head-->20<-->40<-->10<-->30 */
        XorLinkedList xll = new XorLinkedList();
        xll.Insert(10, 1);
        xll.Insert(20, 1);
        xll.Insert(30, 3);
        xll.Insert(40, 2);
 
        // Print the new list
        xll.PrintList();
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Javascript program for the above approach
 
class Node {
    // Constructor to initialize a node with data and npx value
    constructor(data) {
        this.data = data;
        this.npx = 0;
    }
}
 
class XorLinkedList {
    // Constructor to initialize the XOR Linked List
    constructor() {
        this.head = null; // Head node of the XOR Linked List
        this.nodes = []; // Array to store all nodes for dereferencing
    }
 
    // Method to insert a node at a specified position in the XOR Linked List
    insertAtPosition(data, pos) {
        let node = new Node(data); // Create a new node with the given data
        this.nodes.push(node); // Store the node for dereferencing later
 
        // If the XOR Linked List is not empty, update node pointers
        if (this.head !== null) {
            node.npx = getPointer(this.head); // XOR of current node and head node addresses
            this.head.npx = getPointer(node) ^ this.head.npx; // Update head node's npx value
        }
        this.head = node; // Update head to the newly inserted node
        pos -= 1; // Adjust position for array indexing
        let current = this.head; // Initialize current node to head
        let prevAddr = 0; // Address of the previous node (initially 0)
 
        // Traverse the list to reach the insertion position or end of the list
        while (pos > 0 && current != null) {
            let temp = current; // Store a reference to the current node
            let nextAddr = prevAddr ^ current.npx; // Calculate the address of the next node
            prevAddr = getPointer(current); // Update previous node's address
            current = dereferencePointer(nextAddr); // Move to the next node using XOR logic
 
            temp.data = current.data; // Update temporary node's data
            pos -= 1; // Decrement position counter
        }
         
        current.data = data; // Update data of the node at the insertion position
    }
     
    // Method to get the length of the XOR Linked List
    length() {
        let current = this.head; // Initialize current node to head
        let prevAddr = 0; // Address of the previous node (initially 0)
        let count = 0; // Counter to keep track of the number of nodes
         
        // Traverse the list and count nodes until reaching the end
        while (current != null) {
            count += 1; // Increment node count
            let nextAddr = prevAddr ^ current.npx; // Calculate the address of the next node
            prevAddr = getPointer(current); // Update previous node's address
            current = dereferencePointer(nextAddr); // Move to the next node using XOR logic
        }
        return count; // Return the total number of nodes in the list
    }
 
    // Method to print the elements of the XOR Linked List
    printList() {
        let current = this.head; // Initialize current node to head
        let prevAddr = 0; // Address of the previous node (initially 0)
     
        // Traverse the list and print node data until reaching the end
        while (current != null) {
            console.log(current.data); // Print the data of the current node
     
            let nextAddr = prevAddr ^ current.npx; // Calculate the address of the next node
     
            prevAddr = getPointer(current); // Update previous node's address
            current = dereferencePointer(nextAddr); // Move to the next node using XOR logic
        }
    }
}
 
// Map to store addresses of nodes
let addressMap = new Map();
let addressCount = 1;
 
// Function to get the address of a node
function getPointer(object) {
    // If the address of the object is already mapped, return it
    if (addressMap.has(object)) return addressMap.get(object);
 
    let newAddressCountValue = addressCount++; // Increment and get new address count
    addressMap.set(object, newAddressCountValue); // Map the object to its address
 
    return newAddressCountValue; // Return the address of the object
}
 
// Function to dereference an address and retrieve the object
function dereferencePointer(address) {
    for (let [key, value] of addressMap.entries()) {
        if (value === address) return key; // Return the object associated with the address
    }
    return undefined; // Return undefined if address is not found
}
 
// Create an instance of XorLinkedList and perform insertions
let xll = new XorLinkedList();
xll.insertAtPosition(10, 1);
xll.insertAtPosition(20, 1);
xll.insertAtPosition(30, 3);
xll.insertAtPosition(40, 2);
 
// Print the elements of the XOR Linked List
xll.printList();
 
// This code is contributed by Susobhan Akhuli


Python3




# importing necessary modules
import ctypes
 
# creating a node class
 
 
class Node:
    def __init__(self, data):
        self.data = data
        self.link = 0
 
# creating a XOR linked list class
 
 
class XorLinkedList:
        # constructor
    def __init__(self):
        self.head = None
        self.nodes = []
 
    # method to return a new instance of type
    def type_cast(self, id):
        return ctypes.cast(id, ctypes.py_object).value
 
    # method to traverse linked list
 
    def forward_traversal(self):
        # if linked list is empty
        if(self.head == None):
            print("Empty")
        else:
            prev_id = 0
            current = self.head
            # print the first node of linked list
            print(current.data, end=" ")
            next_id = 1
            # print the whole linked list
            while(next_id):
                next_id = prev_id ^ current.link
                if(next_id):
                    prev_id = id(current)
                    current = self.type_cast(next_id)
                    print(current.data, end=" ")
 
    # method to insert a node at a given position
    def insert_at_position(self, key, position):
        # a node can be inserted below 1 position
        if(position < 1):
            print("Can't insert")
        # if node to be inserted at the beginning
        elif(position == 1):
            n = Node(key)
            # if linked list is empty, update the head
            if(self.head == None):
                self.head = n
                # if linked list is not empty, update the link fielf of head, newly inserted node and head pointer.
            else:
                self.head.link = id(n) ^ self.head.link
                n.link = id(self.head)
                self.head = n
            self.nodes.append(n)
        # if node to be inserted at position>1
        else:
            # if linked list is empty and node to be inserted at position>1
            if(self.head == None):
                print("Out of range")
            else:
                n = Node(key)
                current = self.head
                m = id(current)
                i = 1
                prev_id = 0
                next_id = 1
                # Traverse the linked list until desired position is reached
                while(next_id and i < position-1):
                    next_id = prev_id ^ current.link
                    prev_id = id(current)
                    if(next_id):
                        current = self.type_cast(next_id)
                        m = id(current)
                        i = i+1
                    else:
                        break
                if(i == position-1):
 
                    next_id = prev_id ^ current.link
                    current.link = current.link ^ next_id ^ id(n)
 
                    # if position is not the last
                    if(next_id):
                        nxt = self.type_cast(next_id)
                        nxt.link = id(n) ^ nxt.link ^ id(current)
                        n.link = id(current) ^ id(nxt)
                    # if position is the last
                    else:
                        n.link = id(current)
                    self.nodes.append(n)
                # if position exceeds the length of linked list
                else:
                    print("out of range")
 
 
# creating a XOR linked list object
obj = XorLinkedList()
obj.insert_at_position(10, 1)
obj.insert_at_position(20, 1)
obj.insert_at_position(30, 3)
obj.insert_at_position(40, 2)
obj.forward_traversal()


Output

20 40 10 30








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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads