XOR双链表 [英] XOR Doubly Linked List
本文介绍了XOR双链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
因此,作为练习的一部分,我试图创建XOR双链表,但是我的removeFirst()函数始终出现分段错误.我不知道出了什么问题,有人知道吗?
So I am trying to create a XOR Doubly Linked List as part of an exercise, but I keep getting a Segmentation fault on my removeFirst() function. I cannot figure out what is going wrong, does anybody have a clue?
这是一个节点的样子:
class Node{
public:
int data;
Node *XOR;
};
我正在使用此函数来计算XOR:
I am using this function to calculate the XOR:
Node* returnXOR(Node *a, Node *b){
return (Node*)((uintptr_t) (a) ^ (uintptr_t) (b));
}
这是我的异或双链表类:
This is my XOR Doubly Linked List class:
class XORDLL{
public:
Node *head;
XORDLL(){
head = NULL;
}
void addFirst(int data){
// Make a newNode pointer
Node *newNode = new Node;
// Set the variables
newNode->data = data;
newNode->XOR = returnXOR(head, NULL);
// If the head is not empty set the XOR of the head to the next XOR the newNode
if(head != NULL){
head->XOR = returnXOR(newNode, returnXOR(head->XOR, NULL));
}
// Set the newNode to the head
head = newNode;
}
void removeFirst(){
// If head is equal to NULL, do nothing
if(head == NULL){
return;
}
// Store current head
Node *tmp = head;
// Set head equal to the next address
head = returnXOR(tmp->XOR, NULL);
head->XOR = returnXOR(tmp->XOR, tmp);
// Delete tmp variable
delete tmp;
}
void printList(){
Node *current = head;
Node *prev = NULL;
Node *next;
while(current != NULL){
printf("%d ", current->data);
next = returnXOR(current->XOR, prev);
prev = current;
current = next;
}
printf("\n");
}
};
当我运行这段代码时:
int main(){
XORDLL l;
l.addFirst(1);
l.addFirst(2);
l.addFirst(3);
l.printList();
l.removeFirst();
l.printList();
return 0;
}
这是输出:
3 2 1分段错误(核心已转储)
3 2 1 Segmentation fault (core dumped)
推荐答案
您删除
malloc
编辑过的数据.您需要 free
来代替它,或者使用 new
来代替 malloc
.另一个错误是您错过了这一行:
You delete
the malloc
'ed data. You need to free
it instead, or use new
instead of malloc
.
Another bug is that you miss this line:
void removeFirst(){
// If head is equal to NULL, do nothing
if(head == NULL){
return;
}
// Store current head
Node *tmp = head;
// Set head equal to the next address
head = returnXOR(tmp->XOR, NULL);
head->XOR = returnXOR(head->XOR, tmp); <<<<<<<<<<<<<<<<<< Here
// Free tmp variable
free(tmp);
}
这篇关于XOR双链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文