I am currently trying to implement XOR linked list in c++. I tried using template to make it generic. This error pops up during compile time and I cannot get past this.
I tried googling XOR linked list using templates but it seems that there are no implementations of it so far.
XORlinkedlist.h:
#pragma once
#include<iostream>
template <typename T>
struct Node
{
T data;
Node *XORcode;
};
template <typename T>
Node<T> * XOR(struct Node<T> *x, struct Node<T> *y)
{
return (Node<T>*)( (uintptr_t)(x) ^ (uintptr_t)(y) );
}
template <typename T>
class XORlinkedList
{
private:
Node<T> *top, *last;
public:
XORlinkedList()
{
top = last = NULL;
}
void addAtBegin(T data)
{
Node<T> *temp = new Node<T>;
temp->data = data;
temp->XORcode = XOR(top, NULL); //*****ERROR SHOWN IN THIS LINE HERE*****
if(top != NULL)
top->XORcode = XOR(top->XORcode, temp);
top = temp;
}
~XORlinkedList()
{
Node<T> *temp, *storeCode;
temp = top;
storeCode = NULL;
while(top != NULL)
{
temp = top;
top = XOR(top->XORcode, storeCode);
std::cout<<temp->data<<" deleted\n";
storeCode = temp->XORcode;
delete temp;
}
}
};
main.cpp:
#include <iostream>
#include "XORlinkedlist.h"
int main()
{
XORlinkedList<int> X;
X.addAtBegin(3);
X.addAtBegin(4);
X.addAtBegin(5);
std::cin.get();
return 0;
}
The error is:
error C2784: 'Node *XOR(Node *,Node *)' : could not deduce template argument for 'Node *' from 'int'
Compiler can not deduce the argument type because NULL
is not a pointer type. You should overload your method, like this, by using nullptr
, which is an object of an object of type std::nullptr_t
:
// nullptr overload.
template <typename T>
Node<T> * XOR(struct Node<T> *x, std::nullptr_t)
{
return x; // X⊕0 = X
}
template <typename T>
Node<T> * XOR(struct Node<T> *x, struct Node<T> *y)
{
return (Node<T>*)( (uintptr_t)(x) ^ (uintptr_t)(y) );
}
and then, call the method like this:
temp->XORcode = XOR(top, nullptr);
PS: Your constructor's logic seems flawed, probably resulting in a segmentation fault. Read more in Wikipedia or in this C implementation (with an explanation).