Last week, our teacher gave us the task of making a double linked list in C without using two pointers in the structure; we must implement it simply using one pointer to point to the next and previous node in the list. I am convinced that the only way to do this is to use XOR to combine the next and previous directions, and then point to this “hybrid” memory allocation, and if I need the directions of the previous or next, I can use XOR again to get one of the memory values, which I need.
I developed an algorithm, and I thought it would work, but when I tried to implement this solution, I ran into a problem. When I tried to compile the program, the compiler told me that I cannot use XOR (^) for pointers:
invalid operands to binary ^ (have ‘void *’ and ‘node *’)
Here is the function to add node to the top of the list:
typedef struct node_list{
int data;
struct node_list *px;
} node;
node* addfront ( node *root, int data ){
node *new_node, *next;
new_node = malloc ( sizeof ( node ));
new_node -> data = data;
new_node -> px = (NULL ^ root);
if ( root != NULL ){
next = ( NULL ^ root -> px );
root = ( new_node ^ next );
}
}
I read that in C ++, XOR characters are valid. Any ideas on how to implement this in C? I also read somewhere that I need to use intptr_t, but I did not understand what to do with it.
source
share