XOR Linked List - Find the middle node
Last Updated :
16 Feb, 2024
Given an XOR linked list, the task is to find the middle node of the given XOR linked list.
Examples:
Input: 4 –> 7 –> 5
Output: 7
Explanation:
The middle node of the given XOR list is 7.
Input: 4 –> 7 –> 5 –> 1
Output: 7 5
Explanation:
The two middle nodes of the XOR linked list with even number of nodes are 7 and 5.
Approach: Follow the steps below to solve the problem:
- Traverse to (Length / 2)th node of the Linked List.
- If the number of nodes is found to be odd, then print (Length + 1) / 2 th node as the only middle node.
- If the number of nodes is found to be even, then print both Length / 2 th node and (Length / 2) + 1 th node as the middle nodes.
Below is the implementation of the above approach:
C++
// C++ program to implement the above approach
#include <bits/stdc++.h>
#include <inttypes.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)
{
// If XOR linked list is empty
if (*head == NULL) {
// 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 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 = 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;
}
return *head;
}
// Function to print the middle node
int printMiddle(struct Node** head, int len)
{
int count = 0;
// 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;
int middle = (int)len / 2;
// Traverse XOR linked list
while (count != middle) {
// Forward traversal
next = XOR(prev, curr->nxp);
// Update prev
prev = curr;
// Update curr
curr = next;
count++;
}
// If the length of the
// linked list is odd
if (len & 1) {
cout << curr->data << " ";
}
// If the length of the
// linked list is even
else {
cout << prev->data << " " << curr->data << " ";
}
}
// Driver Code
int main()
{
/* Create following XOR Linked List
head --> 4 –> 7 –> 5 */
struct Node* head = NULL;
insert(&head, 4);
insert(&head, 7);
insert(&head, 5);
printMiddle(&head, 3);
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)
{
// 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 the middle node
int printMiddle(struct Node** head, int len)
{
int count = 0;
// 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;
int middle = (int)len / 2;
// Traverse XOR linked list
while (count != middle) {
// Forward traversal
next = XOR(prev, curr->nxp);
// Update prev
prev = curr;
// Update curr
curr = next;
count++;
}
// If the length of the
// linked list is odd
if (len & 1) {
printf("%d", curr->data);
}
// If the length of the
// linked list is even
else {
printf("%d %d", prev->data,
curr->data);
}
}
// Driver Code
int main()
{
/* Create following XOR Linked List
head --> 4 –> 7 –> 5 */
struct Node* head = NULL;
insert(&head, 4);
insert(&head, 7);
insert(&head, 5);
printMiddle(&head, 3);
return (0);
}
Java
import java.util.ArrayList;
// Structure of a node in XOR linked list
class Node {
int value;
int npx; // XOR of next and previous node addresses
public Node(int value) {
this.value = value;
this.npx = 0;
}
}
// XOR Linked List class
class XorLinkedList {
Node head; // head of the XOR linked list
Node tail; // tail of the XOR linked list
ArrayList<Node> nodes; // list to keep track of all nodes in the XOR linked list
// Constructor
public XorLinkedList() {
this.head = null;
this.tail = null;
this.nodes = new ArrayList<>();
}
// Function to insert a node with the given value
void insert(int value) {
// Initialize a new Node
Node node = new Node(value);
// Check if the XOR linked list is empty
if (head == null) {
// Update pointer of head node
head = node;
// Update pointer of tail node
tail = node;
} else {
// Update curr node address
head.npx = System.identityHashCode(node) ^ head.npx;
// Update new node address
node.npx = System.identityHashCode(head);
// Update head
head = node;
}
// Add the node to the list
nodes.add(node);
}
// Method to get the length of the linked list
int length() {
if (!isEmpty()) {
int prevId = 0;
Node node = head;
int nextId = 1;
int count = 1;
while (nextId != 0) {
nextId = prevId ^ node.npx;
if (nextId != 0) {
prevId = System.identityHashCode(node);
node = getTypeCastedNode(nextId);
count++;
} else {
return count;
}
}
}
return 0;
}
// Function to print the middle element(s) of the XOR Linked List
void printMiddle(int length) {
if (head != null) {
int prevId = 0;
Node node = head;
int nextId = 1;
// Traverse XOR linked list
int middle = length / 2;
int count = 0;
Node prev = null;
while (count != middle) {
count++;
// Forward traversal
nextId = prevId ^ node.npx;
if (nextId != 0) {
// Update prev
prevId = System.identityHashCode(node);
// Update curr
prev = node;
node = getTypeCastedNode(nextId);
} else {
return;
}
}
if (length % 2 != 0) {
System.out.print(node.value + " ");
} else {
System.out.print(prev.value + " " + node.value + " ");
}
}
}
// Method to check if the linked list is empty
boolean isEmpty() {
return head == null;
}
// Method to return a new instance of type
Node getTypeCastedNode(int id) {
for (Node n : nodes) {
if (System.identityHashCode(n) == id) {
return n;
}
}
return null;
}
}
public class Main {
public static void main(String[] args) {
// Create XOR Linked List: head --> 4 <--> 7 <--> 5
XorLinkedList xorLinkedList = new XorLinkedList();
xorLinkedList.insert(4);
xorLinkedList.insert(7);
xorLinkedList.insert(5);
// Reverse the XOR Linked List to give: head --> 5 <--> 7 <--> 4
int length = xorLinkedList.length();
xorLinkedList.printMiddle(length);
}
}
Python3
# C program to implement
# the above approach
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)
# method to get length of linked list
def Length(self):
if not self.isEmpty():
prev_id = 0
node = self.head
next_id = 1
count = 1
while next_id:
next_id = prev_id ^ node.npx
if next_id:
prev_id = id(node)
node = self.__type_cast(next_id)
count += 1
else:
return count
else:
return 0
# Function to print elements of the XOR Linked List
def printMiddle(self, length):
if self.head != None:
prev_id = 0
node = self.head
next_id = 1
# Traverse XOR linked list
middle = length // 2
count = 0
prev = None
while count != middle:
count = count + 1
# Forward traversal
next_id = prev_id ^ node.npx
if next_id:
# Update prev
prev_id = id(node)
# Update curr
prev = node
node = self.__type_cast(next_id)
else:
return
if length % 2 != 0:
print(node.value, end = ' ')
else:
print(prev.value, node.value, end = ' ')
# 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
# Create following XOR Linked List
# head-->40<-->30<-->20<-->10
head = XorLinkedList()
head.insert(4)
head.insert(7)
head.insert(5)
# Reverse the XOR Linked List to give
# head-->10<-->20<-->30<-->40
length = head.Length()
head.printMiddle(length)
# This code is contributed by Nidhi goel.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
// Structure of a node in XOR linked list
public class Node {
public int value;
public int
npx; // XOR of next and previous node addresses
public Node(int value)
{
this.value = value;
this.npx = 0;
}
}
// XOR Linked List class
public class XorLinkedList {
Node head; // head of the XOR linked list
List<Node> nodes; // list to keep track of all nodes in
// the XOR linked list
// Constructor
public XorLinkedList()
{
this.head = null;
this.nodes = new List<Node>();
}
// Function to insert a node with the given value
public void Insert(int value)
{
// Initialize a new Node
Node node = new Node(value);
// Check if the XOR linked list is empty
if (head == null) {
// Update pointer of head node
head = node;
}
else {
// Update curr node address
head.npx = RuntimeHelpers.GetHashCode(node)
^ head.npx;
// Update new node address
node.npx = RuntimeHelpers.GetHashCode(head);
// Update head
head = node;
}
// Add the node to the list
nodes.Add(node);
}
// Method to get the length of the linked list
public int Length()
{
if (!IsEmpty()) {
int prevId = 0;
Node node = head;
int nextId = 1;
int count = 1;
while (nextId != 0) {
nextId = prevId ^ node.npx;
if (nextId != 0) {
prevId
= RuntimeHelpers.GetHashCode(node);
node = GetTypeCastedNode(nextId);
count++;
}
else {
return count;
}
}
}
return 0;
}
// Function to print the middle element(s) of the XOR
// Linked List
public void PrintMiddle(int length)
{
if (head != null) {
int prevId = 0;
Node node = head;
int nextId = 1;
// Traverse XOR linked list
int middle = length / 2;
int count = 0;
Node prev = null;
while (count != middle) {
count++;
// Forward traversal
nextId = prevId ^ node.npx;
if (nextId != 0) {
// Update prev
prevId
= RuntimeHelpers.GetHashCode(node);
// Update curr
prev = node;
node = GetTypeCastedNode(nextId);
}
else {
return;
}
}
if (length % 2 != 0) {
Console.Write(node.value + " ");
}
else {
Console.Write(prev.value + " " + node.value
+ " ");
}
}
}
// Method to check if the linked list is empty
public bool IsEmpty() { return head == null; }
// Method to return a new instance of type
public Node GetTypeCastedNode(int id)
{
foreach(Node n in nodes)
{
if (RuntimeHelpers.GetHashCode(n) == id) {
return n;
}
}
return null;
}
}
public class GFG {
public static void Main(string[] args)
{
// Create XOR Linked List: head --> 4 <--> 7 <--> 5
XorLinkedList xorLinkedList = new XorLinkedList();
xorLinkedList.Insert(4);
xorLinkedList.Insert(7);
xorLinkedList.Insert(5);
// Reverse the XOR Linked List to give: head --> 5
// <--> 7 <--> 4
int length = xorLinkedList.Length();
xorLinkedList.PrintMiddle(length);
}
}
// This code is contributed by Susobhan Akhuli
JavaScript
// JavaScript program to implement the above approach
class Node {
constructor(value) {
this.value = value;
this.npx = 0;
}
}
// create linked list class
class XorLinkedList {
// constructor
constructor() {
this.head = null;
this.tail = null;
this.__nodes = [];
}
// Function to insert a node with given value at given position
insert(value) {
// Initialize a new Node
const node = new Node(value);
// Check If XOR linked list is empty
if (this.head === null) {
// Update pointer of head node
this.head = node;
// Update pointer of tail node
this.tail = node;
} else {
// Update curr node address
this.head.npx = this.__getId(node) ^ this.head.npx;
// Update new node address
node.npx = this.__getId(this.head);
// Update head
this.head = node;
}
// push node
this.__nodes.push(node);
}
// method to get length of linked list
length() {
if (!this.isEmpty()) {
let prevId = 0;
let node = this.head;
let nextId = 1;
let count = 1;
while (nextId) {
nextId = prevId ^ node.npx;
if (nextId) {
prevId = this.__getId(node);
node = this.__typeCast(nextId);
count += 1;
} else {
return count;
}
}
} else {
return 0;
}
}
// Function to print elements of the XOR Linked List
printMiddle(length) {
if (this.head !== null) {
let prevId = 0;
let node = this.head;
let nextId = 1;
// Traverse XOR linked list
const middle = Math.floor(length / 2);
let count = 0;
let prev = null;
while (count !== middle) {
count = count + 1;
// Forward traversal
nextId = prevId ^ node.npx;
if (nextId) {
// Update prev
prevId = this.__getId(node);
// Update curr
prev = node;
node = this.__typeCast(nextId);
} else {
return;
}
}
if (length % 2 !== 0) {
console.log(node.value);
} else {
console.log(prev.value, node.value);
}
}
}
// method to check if the linked list is empty or not
isEmpty() {
if (this.head === null) {
return true;
}
return false;
}
// method to return a new instance of type
__typeCast(id) {
return ctypes.cast(id, ctypes.py_object).value;
}
// method to get the unique ID of an object
__getId(obj) {
return obj && obj.__unique_id__;
}
}
// Create following XOR Linked List
// head-->40<-->30<-->20<-->10
const head = new XorLinkedList();
head.insert(4);
head.insert(5);
head.insert(7);
// Reverse the XOR Linked List to give
// head-->10<-->20<-->30<-->40
const length = head.length();
head.printMiddle(length);
//this is generated by chetanbargal
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Find Middle of the Linked List Given a singly linked list, the task is to find the middle of the linked list. If the number of nodes are even, then there would be two middle nodes, so return the second middle node.Example:Input: linked list: 1->2->3->4->5Output: 3 Explanation: There are 5 nodes in the linked list and
14 min read
Insert node into the middle of the linked list Given a linked list containing n nodes. The problem is to insert a new node with data x in the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.Examples: Input: LinkedList = 1->2->4 , x = 3Output: 1->2->3
14 min read
XOR Linked List - Find Nth Node from the end Given a XOR linked list and an integer N, the task is to print the Nth node from the end of the given XOR linked list. Examples: Input: 4 â> 6 â> 7 â> 3, N = 1 Output: 3 Explanation: 1st node from the end is 3.Input: 5 â> 8 â> 9, N = 4 Output: Wrong Input Explanation: The given Xor Li
15+ min read
Make middle node head in a linked list Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input : 1 2 3 4 5 Output : 3 1 2 4 5 Input : 1 2 3 4 5 6 Output : 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one m
10 min read
Find kth node from Middle towards Head of a Linked List Given a Linked List and a number K. The task is to print the value of the K-th node from the middle towards the beginning of the List. If no such element exists, then print "-1". Note: The position of the middle node is: (n/2)+1, where n is the total number of nodes in the list. Examples: Input : Li
14 min read