Search code examples
c++xor-linkedlist

xor linked list implementation


here is my code for xor linked list implementation

#include<iostream>

using namespace std;

struct node
{
    int v;
    node *next;
};

node *start=NULL;
node *end=NULL;

node *newnode(int v)
{
    node *np=new node;
    np->v=v;
    np->next=NULL;
    return np;
}

//returns the xor of two nodes
node *xor(node *a,node *b)
{
    return (node*)((long long)(a)^(long long)(b));
}

void insert(node *current,node *prev,node *np)
{
    if(start==NULL)
    {
        np->next=xor(prev,NULL);
        start=np;
        end=np;
    }
    else
    {
        insert(xor(prev,current->next),current,np);
    }
}

void displayforward(node *start,node *prev)
{
    if(start==NULL) return ;
    cout<<start->v<<"-> ";
    displayforward(xor(start->next,prev),start);
}

void displayBackward(node *end, node *prev){
    if(end == NULL) return;

    cout<< end->v<<" -> ";
    displayBackward( xor(end->next, prev), end);
}

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9,10}, n = 10;

    for(int i=0; i < n; i++){
        node *prev = NULL;
        insert(start, prev, newnode(a[i]));
    }

    cout<<"Forward: \n";
    node *prev=NULL;
    displayforward(start, prev);

    cout<<"\nBackward: \n";
    displayBackward(end, prev);

    return 0;
}

but when i compile it,it gives me error like this

1>------ Build started: Project: xor_list, Configuration: Debug Win32 ------
1>  xor_list.cpp
1>c:\users\daviti\documents\visual studio 2010\projects\xor_list\xor_list\xor_list.cpp(30): error C2872: 'end' : ambiguous symbol
1>          could be 'c:\users\daviti\documents\visual studio 2010\projects\xor_list\xor_list\xor_list.cpp(9) : node *end'
1>          or       'end'
1>c:\users\daviti\documents\visual studio 2010\projects\xor_list\xor_list\xor_list.cpp(69): error C2872: 'end' : ambiguous symbol
1>          could be 'c:\users\daviti\documents\visual studio 2010\projects\xor_list\xor_list\xor_list.cpp(9) : node *end'
1>          or       'end'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

why it is ambigious symbol end?what does this error mean?


Solution

  • The compiler is unsure whether to use your end global variable or the std::end symbol, which happens to be a function returning an iterator to the end of a container. That it doesn't make much sense to assign anything to that symbol is a different matter. Remove the using namespace std; directive to fix this particular problem. I would suggest replacing it with using std::cout; to avoid polluting the namespace.