上周,我们的老师给了我们一个任务,在不使用两个指针的情况下用C语言制作双向链表;我们必须只使用一个指针来实现对列表中下一个和上一个节点的指向。我相信唯一的方法是使用异或(XOR)合并下一个和上一个方向,然后指向那个“混合”内存分配,如果我需要 prev 或 next 的方向,我可以再次使用 XOR 获取我需要的任一内存值。
我设计了算法,认为它会起作用,但当我尝试实现解决方案时,遇到了一个问题。当我尝试编译程序时,编译器告诉我不能使用 XOR (^) 来指向指针:
这是在链表头部添加节点的函数:
我设计了算法,认为它会起作用,但当我尝试实现解决方案时,遇到了一个问题。当我尝试编译程序时,编译器告诉我不能使用 XOR (^) 来指向指针:
invalid operands to binary ^ (have ‘void *’ and ‘node *’)
这是在链表头部添加节点的函数:
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);//this will be the new head of the list
if ( root != NULL ){ // if the list isn't empty
next = ( NULL ^ root -> px ); // "next" will be the following node of root, NULL^(NULL^next_element).
root = ( new_node ^ next ); //now root isn't the head node, so it doesn't need to point null.
}
}
我读到在C++中,对指针使用XOR是有效的。你有什么想法可以在C语言中实现这个功能吗?我还在某个地方看到需要使用 intptr_t
,但我不知道该怎么做。
root->px
等方式。 - Jonathan LefflermyType * ptr = (myType *)(((void *)a) ^ ((void *)b));
会导致VS 2017编译器出错,显示为error C2296: '^': illegal, left operand has type 'void *'
和error C2297: '^': illegal, right operand has type 'void *'
。 - JamesThomasMoon