【发布时间】:2014-12-21 13:53:41
【问题描述】:
上周,我们的老师给了我们一个作业,在 C 语言中创建一个双链表,而不在结构中使用两个指针;我们必须使用一个指针来实现它,以指向列表中的下一个和上一个节点。我确信这样做的唯一方法是使用 XOR 来合并下一个和上一个方向,然后指向那个“混合”内存分配,如果我需要 prev 或 next 的方向,我可以再次使用 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,但我不明白如何处理它。
【问题讨论】:
-
@Affess 我认为 OP 知道算法是如何工作的,只是不知道实现它的确切 C 构造。
-
.和->运算符绑定得非常紧密;在它们周围留出空间是一种惯例。始终使用root->px等。 -
对于 googlers,从声明
myType * ptr = (myType *)(((void *)a) ^ ((void *)b));错误 VS 2017 编译器为error C2296: '^': illegal, left operand has type 'void *和error C2297: '^': illegal, right operand has type 'void *'。