XOR linked list- Remove first node of the linked list
Last Updated :
10 Apr, 2023
Given an XOR linked list, the task is to remove the first node of the XOR linked list.
Examples:
Input: XLL = 4 < – > 7 < – > 9 < – > 7
Output: 7 < – > 9 < – > 7
Explanation: Removing the first node of the XOR linked list modifies XLL to 7 < – > 9 < – > 7
Input: XLL = NULL
Output: List Is Empty
Approach: The idea is to update the head node of the XOR linked list to the second node of the XOR linked list and delete memory allocated for the first node. Follow the steps below to solve the problem:
- Check if the XOR linked list is empty or not. If found to be true, then print "List Is Empty".
- Otherwise, update the head node of the XOR linked list to the second node of the linked list.
- Delete the first node from memory.
Below is the implementation of the above approach:
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 address 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)
{
// Check If XOR linked list
// is empty
if (*head == NULL) {
// 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 the XOR linked list
// is not empty
else {
// Stores the address
// of current node
struct Node* curr = *head;
// Stores the address
// of previous node
struct Node* prev = NULL;
// 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;
}
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;
}
}
// Function to remove the first node from
// the given linked list
struct Node* delBeginning(struct Node** head)
{
// If list is empty
if (*head == NULL)
printf("List Is Empty");
else {
// Store the node to be deleted
struct Node* temp = *head;
// Update the head pointer
*head = XOR(NULL, temp->nxp);
// When the linked list
// contains only one node
if (*head != NULL) {
// Update head node address
(*head)->nxp
= XOR(NULL, XOR(temp,
(*head)->nxp));
}
free(temp);
}
return *head;
}
// Driver Code
int main()
{
/* Create following XOR Linked List
head-->40<-->30<-->20<-->10 */
struct Node* head = NULL;
insert(&head, 10);
insert(&head, 20);
insert(&head, 30);
insert(&head, 40);
// Delete the first node
delBeginning(&head);
/* Print the following XOR Linked List
head-->30<-->20<-->10 */
printList(&head);
return (0);
}
C++
#include <iostream>
#include <cstdlib>
using namespace std;
// Structure of a node in XOR linked list
struct Node {
int data;
struct Node* nxp;
};
// Function to find the XOR of address 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)
{
// Check If XOR linked list is empty
if (*head == NULL)
{
// 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 the XOR linked list is not empty
else
{
// Stores the address of current node
struct Node* curr = *head;
// Stores the address of previous node
struct Node* prev = NULL;
// 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;
}
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;
}
}
// Function to remove the first node from the given linked list
struct Node* delBeginning(struct Node** head)
{
// If list is empty
if (*head == NULL)
cout << "List Is Empty";
else
{
// Store the node to be deleted
struct Node* temp = *head;
// Update the head pointer
*head = XOR(NULL, temp->nxp);
// When the linked list contains only one node
if (*head != NULL)
{
// Update head node address
(*head)->nxp = XOR(NULL, XOR(temp, (*head)->nxp));
}
free(temp);
}
return *head;
}
int main()
{
/* Create following XOR Linked List
head-->40<-->30<-->20<-->10 */
struct Node* head = NULL;
insert(&head, 10);
insert(&head, 20);
insert(&head, 30);
insert(&head, 40);
// Delete the first node
delBeginning(&head);
/* Print the following XOR Linked List
head-->30<-->20<-->10 */
printList(&head);
return (0);
}
// This code is contributed by lokeshpotta20.
Java
import java.util.HashMap;
import java.util.Map;
class Node {
int data;
int npx;
Node(int data) {
this.data = data;
this.npx = 0;
}
}
class XorLinkedList {
Node head;
Node[] nodes;
XorLinkedList() {
head = null;
nodes = new Node[100]; // assuming 100 as max number of nodes
}
void insert(int data) {
Node node = new Node(data);
nodes[data - 1] = node; // assuming data starts from 1 and is unique
if (head != null) {
node.npx = getPointer(head);
head.npx = getPointer(node) ^ head.npx;
}
head = node;
}
void removeHead() {
if (head == null) {
System.out.println("List Is Empty");
return;
}
int nextNodeId = head.npx;
if (nextNodeId != 0) {
Node nextNode = dereferencePointer(nextNodeId);
nextNode.npx ^= getPointer(head);
nodes[head.data - 1] = null; // removing head node from nodes array
head = nextNode;
}
}
void printList() {
Node current = head;
int prevAddr = 0;
while (current != null) {
System.out.println(current.data);
int nextAddr = prevAddr ^ current.npx;
prevAddr = getPointer(current);
current = dereferencePointer(nextAddr);
}
}
int getPointer(Node node) {
// Using System.identityHashCode to get a unique identifier for the node object
return System.identityHashCode(node);
}
Node dereferencePointer(int address) {
for (int i = 0; i < nodes.length; i++) {
if (nodes[i] != null && getPointer(nodes[i]) == address) {
return nodes[i];
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
XorLinkedList xll = new XorLinkedList();
xll.insert(10);
xll.insert(20);
xll.insert(30);
xll.insert(40);
xll.removeHead();
xll.printList();
}
}
Python3
import ctypes
# Structure of a node in XOR linked list
class Node:
def __init__(self, value):
self.value = value
self.npx = 0
# create linked list class
class XorLinkedList:
# constructor
def __init__(self):
self.head = None
self.tail = None
self.__nodes = []
# Function to insert a node with given value at given position
def insert(self, value):
# Initialize a new Node
node = Node(value)
# Check If XOR linked list is empty
if self.head is None:
# Update pointer of head node
self.head = node
# Update pointer of tail node
self.tail = node
else:
# Update curr node address
self.head.npx = id(node) ^ self.head.npx
# Update new node address
node.npx = id(self.head)
# Update head
self.head = node
# push node
self.__nodes.append(node)
# Function to print elements of the XOR Linked List
def printList(self):
if self.head != None:
prev_id = 0
node = self.head
next_id = 1
print(node.value, end=' ')
# Traverse XOR linked list
while next_id:
# Forward traversal
next_id = prev_id ^ node.npx
if next_id:
# Update prev
prev_id = id(node)
# Update curr
node = self.__type_cast(next_id)
# Print current node
print(node.value, end=' ')
else:
return
# method to check if the linked list is empty or not
def isEmpty(self):
if self.head is None:
return True
return False
# method to return a new instance of type
def __type_cast(self, id):
return ctypes.cast(id, ctypes.py_object).value
# Function to remove the first node from the given linked list
def delBeginning(self):
# If list is empty
if self.isEmpty():
return "List is empty !"
# If list has 1 node
elif self.head == self.tail:
self.head = self.tail = None
# If list has 2 nodes
elif (0 ^ self.head.npx) == id(self.tail):
self.head = self.tail
self.head.npx = self.tail.npx = 0
# If list has more than 2 nodes
else:
# Store the node to be deleted
res = self.head.value
# Address of next node
x = self.__type_cast(0 ^ self.head.npx)
# Address of next of next node
y = (id(self.head) ^ x.npx)
self.head = x
self.head.npx = 0 ^ y
return res
# Create following XOR Linked List
# head-->40<-->30<-->20<-->10
head = XorLinkedList()
head.insert(10)
head.insert(20)
head.insert(30)
head.insert(40)
# Delete the first node
head.delBeginning();
# Print the following XOR Linked List
# head-->30<-->20<-->10
head.printList();
# This code is contributed by Nighi goel.
C#
using System;
class Node {
public int data;
public int npx;
public Node(int data) {
this.data = data;
this.npx = 0;
}
}
class XorLinkedList {
private Node head;
private Node[] nodes;
public XorLinkedList() {
head = null;
nodes = new Node[100]; // assuming 100 as max number of nodes
}
public void insert(int data) {
Node node = new Node(data);
nodes[data - 1] = node; // assuming data starts from 1 and is unique
if (head != null) {
node.npx = getPointer(head);
head.npx = getPointer(node) ^ head.npx;
}
head = node;
}
public void removeHead() {
if (head == null) {
Console.WriteLine("List Is Empty");
return;
}
int nextNodeId = head.npx;
if (nextNodeId != 0) {
Node nextNode = dereferencePointer(nextNodeId);
nextNode.npx ^= getPointer(head);
nodes[head.data - 1] = null; // removing head node from nodes array
head = nextNode;
}
}
public void printList() {
Node current = head;
int prevAddr = 0;
while (current != null) {
Console.WriteLine(current.data);
int nextAddr = prevAddr ^ current.npx;
prevAddr = getPointer(current);
current = dereferencePointer(nextAddr);
}
}
private int getPointer(Node node) {
// Using RuntimeHelpers.GetHashCode to get a unique identifier for the node object
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(node);
}
private Node dereferencePointer(int address) {
for (int i = 0; i < nodes.Length; i++) {
if (nodes[i] != null && getPointer(nodes[i]) == address) {
return nodes[i];
}
}
return null;
}
}
public class Program {
public static void Main() {
XorLinkedList xll = new XorLinkedList();
xll.insert(10);
xll.insert(20);
xll.insert(30);
xll.insert(40);
xll.removeHead();
xll.printList();
}
}
JavaScript
class Node {
constructor(data) {
this.data = data;
this.npx = 0;
}
}
class XorLinkedList {
constructor() {
this.head = null;
this.nodes = [];
}
insert(data) {
let node = new Node(data);
this.nodes.push(node);
if (this.head !== null) {
node.npx = getPointer(this.head);
this.head.npx = getPointer(node) ^ this.head.npx;
}
this.head = node;
}
removeHead() {
if (!this.head) {
console.log("List Is Empty");
return;
}
let nextNodeId = this.head.npx;
if (nextNodeId !== 0) {
let nextNode = dereferencePointer(nextNodeId);
nextNode.npx ^= getPointer(this.head);
delete this.nodes[this.nodes.indexOf(this.head)];
delete this.head;
this.head = nextNode;
}
}
printList() {
let current = this.head;
let prevAddr = 0;
while (current != null) {
console.log(current.data);
let nextAddr = prevAddr ^ current.npx;
prevAddr = getPointer(current);
current = dereferencePointer(nextAddr);
}
}
}
let addressMap = new Map();
let addressCount = 1;
function getPointer(object) {
if (addressMap.has(object)) return addressMap.get(object);
let newAddressCountValue = addressCount++;
addressMap.set(object, newAddressCountValue);
return newAddressCountValue;
}
function dereferencePointer(address) {
for (let [key, value] of addressMap.entries()) {
if (value === address) return key;
}
return undefined
}
let xll = new XorLinkedList();
xll.insert(10);
xll.insert(20);
xll.insert(30);
xll.insert(40);
xll.removeHead();
xll.printList();
Time Complexity: O(1)
Auxiliary Space: O(1)
Similar Reads
XOR Linked List: Remove last node of the Linked List Given an XOR linked list, the task is to delete the node at the end of the XOR Linked List. Examples: Input: 4<â>7<â>9<â>7Output: 4<â>7<â>9Explanation: Deleting a node from the end modifies the given XOR Linked List to 4<â>7<â>9 Input: 10Output: List is empt
15+ min read
Convert Singly Linked List to XOR Linked List Prerequisite: XOR Linked List â A Memory Efficient Doubly Linked List | Set 1XOR Linked List â A Memory Efficient Doubly Linked List | Set 2 An XOR linked list is a memory efficient doubly linked list in which the next pointer of every node stores the XOR of previous and next node's address. Given a
9 min read
Remove Nth node from end of the Linked List Given a linked list. The task is to remove the Nth node from the end of the linked list.Examples: Input : LinkedList = 1 ->2 ->3 ->4 ->5 , N = 2Output : 1 ->2 ->3 ->5Explanation: Linked list after deleting the 2nd node from last which is 4, is 1 ->2 ->3 ->5 Input : Link
15+ min read
Remove the common nodes in two Singly Linked Lists Given two Linked Lists L1 and L2, the task is to generate a new linked list with no common elements from the given two linked lists. Example: Input: L1 = 10 -> 15 -> 5 -> 20, L2 = 8 -> 5 -> 20 -> 10 Output: 8 -> 15 Explanation: Since both the linked list has 5, 10 and 20 in comm
10 min read
Remove all occurrences of one Linked list in another Linked list Given two linked lists head1 and head2, the task is to remove all occurrences of head2 in head1 and return the head1. Examples: Input: head1 = 2 -> 3 -> 4 -> 5 -> 3 -> 4, head2 = 3 -> 4Output: 2 -> 5Explanation: After removing all occurrences of 3 -> 4 in head1 output is 2 -
9 min read
Deletion at end (Removal of last node) in a Linked List Given a linked list, the task is to delete the last node of the given linked list.Examples:Â Â Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULLOutput: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 3 -> 12 -> 15-> NULLOutput
8 min read